What does "if var" mean in python?

Behaviour differs a little bit from language to language.

Behaviour 1: The variable is converted into a boolean. I.e. there are language specific conversions from different types into a boolean. For numeric values, 0 is usually converted into false while any other value is converted to true. As far as I know, this is the way Python does it.

Behaviour 2: Booleans are numeric values. As above, 0 is usually the only value that evaluates to false

Behaviour 3: Any non-null reference evaluates to true, null references evaluate to false.

This should more or less cover it, but there may be other variations or combinations as well, for instance using fallback to method 2 or 3 if 1 is not available. The point is that it's very much a language specific question.


in python, writing

if var:

has the same effect as writing

if bool(var):

(where bool is the built-in bool type which also acts as a constructor function for bool objects).

If the value is already a bool (valued True or False) the meaning is clear -- bool(var) returns the same value. For other types, there's almost always a conversion to bool avaliable which depends on the type. For integers (as in C) it's the same as var!=0; for lists or dicts or strings, it's the same as len(var)!=0, and so forth. You can find this in the python docs.

When you define your own class you can define a method via def __nonzero__(self): , which will be called in this context (when your object is passed to bool explicitly, or implicitly in an if -- or while for that matter).

A notable exception: numpy array objects do not convert to bool (they raise an exception). They need to be explicitly converted using constructs like (arr!=0).any() or (arr>0).all()

On similar lines: Don't get into the habit of writing any of

if x == True:     # This only works as expected when x is a bool, or 0, or 1
if x is True:     # Can be useful but you need to understand what it really means.
if x == None:     # Often works as expected, except when it doesn't

Comparison to None should always be done with

if x is None: (or) if x is not None:

There is only one None object, and x is None will tell you if x refers to that object, and will always give you a bool (True if so, False for any other object). Comparing x==None (a mistake I frequently made when starting to use Python) will usually work, but it activates the generic comparison machinery of Python, which is not what you probably want; if x is an instance of a class, the comparison could raise an exception. is is simple and quick and just does that identity test - it can't be overloaded.

Likewise if x is True means "if x is the boolean object meaning true, and no other object at all" -- which can be useful, but is too narrow for the case when you are just testing truth value. Somebody might end up passing 1, which will fail an 'is True' test, but otherwise acts very much like True.