Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this Python expression make sense?

I found this kind of expression several times in a python program:

if variable is not None:
    dothings(variable)

It seems strange to me, and I think that it has no more sense than:

if variable:
    dothings(variable)

Maybe I don't know Python enough, and the expression is explained somewhere?

like image 378
Zhen Avatar asked Nov 29 '12 15:11

Zhen


2 Answers

variable could be 0, or False, or [], or (); be 'falsy' in other words, and then the if statement would be skipped.

See Truth testing for more detail on what is considered false in a boolean context.

In short, testing if variable is not None allows variable to be anything else, including values that would otherwise be considered False in a boolean context.

like image 59
Martijn Pieters Avatar answered Sep 30 '22 00:09

Martijn Pieters


Some values are falsy, but are not None. You may still want to dothings() to those values.

Here are the things that are falsy in Python 2. (You may want to change the '2' in the URL to a '3' to get the values for Python 3, but it didn't change much.)

like image 28
kojiro Avatar answered Sep 30 '22 00:09

kojiro