None

One thing that caught me out recently (and not just me from what google tells me) is Python’s treating of empty data structures as false. A sort of NULL pointers in C. Coming from a C/C++ background, I love writing code like this:

<pre>
def func(param):
if param:
print “param is not empty”
else:
print “param is empty”
</pre>

param can be an empty dictionary {}, an empty list [], an empty tuple, or an empty string “”. I love this syntax.
Python treats these empty data structures as False.
However, Python also treats None like False. None is possibly closer to what NULL is in C.

The only problem is when you write code where you need to distinguish between 3 states:
a. non-empty data structure
b. empty data structure
c. not found (or any other error)

Solving this sort of puzzles doesn’t map very well to a boolean True/False representation. Below there’s some code that I wrote recently and got me into trouble. To preserve anonymity, I’ve changed the names of the main actors 🙂

<pre>

mobile_number = person.get(“mobile_number”, None)
if mobile_number:
print “Mobile number is:”, mobile_number
else:
print “No mobile number?!”

</pre>

Assuming person is a dictionary, this line of code tries to get the value for the “mobile_number” key, or, if the key doesn’t exist, return None. Pretty decent, until you realize that you cannot distinguish between the case where the mobile_number key is missing or the mobile_number is the empty string.

Maybe in this case it’s not important to distinguish between the None value or the empty string. But you can surely imagine a case where an empty string would be a valid value, but not a missing key.

The solution is to explicitly check for None as in the example below:

<pre>

mobile_number = person.get(“mobile_number”, None)
if mobile_number is None:
print “Mobile number is missing”
elif mobile_number:
print “Mobile number is:”, mobile_number
else:
print “Mobile number is empty”

</pre>

Advertisements

Tags: , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s


%d bloggers like this: