Q. When is a Boolean not a Boolean?

A. In the hands of dodgy Python developers ;^)

I just came across an example of my least-favourite(?) anti-pattern in Python – using “implicit” boolean values in conditional expressions. This particular occurrence was found in sample code in the “Google App Engine”, but it could have come from lots of places ;^)

...
user = users.get_current_user()
if user:
   # Do something...

else:
  # Re-direct to login page
...

The “get_current_user” method returns None if there is no user currently logged in, hence the poorly written “if user” test.

Now this is (obviously) perfectly valid code because in Python, empty lists, dicts, 0 (zero), None etc all evaluate to False, whereas a list or dict with at least one item, a non-zero integer, a non-None reference to an object etc. all evaluate to True…

Well, almost… and therein lies the problem! If, for example, an object instance implements the special method “__len__” and happens to return zero then it too would evaluate to False. Maybe what you wanted, and maybe not, but in my experience this has caused some weird, wonderful and subtle bugs (the best kind ;^). IMHO it is much better to use explicit boolean expressions where, errr, booleans are expected, and hence the above example should be:-

user = users.get_current_user()
if user is not None:
   # Do something...

else:
  # Re-direct to login page

I’m not sure why some Python developers insist on using the above pattern – do they really think that the typing it saved them reduced the overall development time? If so, maybe they also think of themselves as typists, not developers ;^)

Leave a Reply

Your email address will not be published. Required fields are marked *