Musings of an anonymous geek

May 22, 2007

Python: “Which of these variables is None?”

Filed under: Python,Scripting,Technology — m0j0 @ 8:39 am

So I’m still getting past the neophyte stage with Python. The good news is that every time I need to apply some programming principle to something I’m doing in Python, it’s really very easy. Heck, I practically fell accidentally into OO programming on one of my Python projects, and everything else has been a dream so far as well.

One problem I was having with one of my projects was kind of an academic issue: I wanted a very concise way to tell what the status of two variables was. My code needed to do different things based on each possible scenario. After tossing about my brain for a while, I decided to take the easy way out and write an “if” block to handle this. Here’s the “if” block:

if a == '' and b == '':
indicator = 0
if a != '' and b == '':
indicator = -1
if a == '' and b != '':
indicator = 1
if a != '' and b != '':
indicator = 2

This does the job, but it’s long, and not the most elegant of possible solutions. Some people online started getting into some rather obfuscated solutions to the issue, and when people started asking if Python supported bit-shifting, I decided to just leave it and move on (I actually never did find out if it was supported). After all, someone else is going to have to read my code at some point!

Then I spoke to a fellow member of my local LUG and Python enthusiast Dr. Jon Fox, and he tossed out this solution that is so cool, and so readable, and so elegant, that it just made me want to slash myself in half with a bread knife. Here it is:

whoisNone = lambda a,b: (a == None) + 2*(b==None)

The above can, of course, be written as a function that takes any two variables you care to pass to it. The above one-liner returns 0 if neither is None. Returns 1 if the first is None but the second is not, Returns 2 if the first is not but the second is None. Returns 3 if both are None.

This is precisely what I was looking for. Thanks Dr. Fox!

Technorati Tags: , , ,

Social Bookmarks:

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Blog at

%d bloggers like this: