In recent code in the IssueTrackerProduct I needed to have a cgi parameter called remember-filterlogic so the URL might look like this: ListIssues?rememeber-filterlogic=no&Filterlogic=show. Because I want the cgi parameters to look human I had to write the following little utility function:


def niceboolean(value):
   falseness = ('','no','off','false','none','0', 'f')
   return str(value).lower().strip() not in falseness

It basically converts what you say to what you mean. In Python "f" is a one letter string and would normally mean True, but since humans are involved here it from means something else for a moment. What do you think?

UPDATE: The code has changed since the comment below by Ben Young. The code had a missing not which made the code return True on Off and False on On.

UPDATE 2: The emptystring "" is now also False.

Comments

Post your own comment
Ben Young

Doesn't that return True if the value is in falseness? Also I would reverse the sense, so that anything not recognised counts as False, so that garbage != True

Peter

You're absolutely right. I'm such a fool.

The code was written differently in the code I copied it from and in a clumsy editing to make it neater I forgot to check that it still did as expected. Thank you.

Anonymous

To catch errors early, you could explicitly check for `trueness' and raise ValueError when `value' is in neither list.

Peter

I don't understand what you mean. Please explain. Certainly the above code can be done in different ways but what's interesting is what it can do. Here is some output from a unit test:

False -> False
True -> True
1 -> True
0 -> False
'1' -> True
'0' -> False
'On' -> True
'Off' -> False
'False' -> False
'No' -> False
'Yes' -> True
'T' -> True
'F' -> False

Ben Young

I think what anonymous means is, what does the unit tests give for
'fish'
''
'nope'
etc

Peter

'fish' and 'nope' must fall back on the default which is True.

It's a bug that '' isn't considered False I think. Will update the code.

Your email will never ever be published.

Previous:
parametrize_url() adding parameters to URLs January 14, 2005 Python
Next:
Google is blind January 24, 2005 Web development
Related by category:
A Python dict that can report which keys you did not use June 12, 2025 Python
Faster way to sum an integer series in Python August 28, 2025 Python
Combining Django signals with in-memory LRU cache August 9, 2025 Python
Native connection pooling in Django 5 with PostgreSQL June 25, 2025 Python