niceboolean() - converts what you say to what you mean

21 January 2005   6 comments   Python

Mind That Age!

This blog post is 13 years old! Most likely, its content is outdated. Especially if it's technical.

Powered by Fusion×

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.


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
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.
To catch errors early, you could explicitly check for `trueness' and raise ValueError when `value' is in neither list.
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' 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.
Thank you for posting a comment

Your email will never ever be published

Related posts

parametrize_url() adding parameters to URLs 14 January 2005
Google is blind 24 January 2005
Related by Text:
Interesting float/int casting in Python 25 April 2006
cache_memoize - a pretty decent cache decorator for Django 11 September 2017
bool is instance of int in Python 05 December 2008
AJAX accelerated web widgets 23 June 2005
slim, a new free web service for white space optimisation 25 July 2006