Uncategorized

A python gotcha

One “gotcha” that stumped me a few times when I started out programming in python was around the use of boolean operators, especially the “and” operator.

A typical use case of “and” is the following:

An example that’s a little bit more complicated is something like this:


The output is as expected:

>> I can purchase apples
>> I can’t purchase donuts

But if we later write unit tests for the function, we get an error.

>> AssertionError: 8 != True

The “gotcha” here is that function can_purchase is not returning a boolean.

If you read the python documentation on Boolean Operations carefully, you’ll see the following table.

Operation Result Notes
x or y if x is false, then y, else x (1)
x and y if x is false, then x, else y (2)
not x if x is false, then True, else False (3)

You’re guaranteed a boolean when you use the “not” operator, but not when using “or” or “not”.

This was a little bit more obvious for the “or” operator as it’s widely used for setting a default value when looking up elements in a dictionary.

The easiest solution is to properly return a boolean,

but people may simply forget to do so. Boolean operators can also be chained, making the problem less obvious at first.

Do you remember any fun “gotchas” from when you started programming in python?

Discussion

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

Pingbacks & Trackbacks

  1. A Note About Comparisons | Jana Technology