9

I'm new to Python and I'm playing a bit with some code snippets.

In my code I need to check for variable initialization and I was using this idiom:

if my_variable:
    # execute some code

but reading some posts I found this other idiom is used:

if my_variable is not None:
    # execute some code

Are they equivalent or is there some semantic difference?

5 Answers 5

11

Quoting Python documentation on boolean operations,

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

So, if my_variable will fail, if my_variable has any of the above mentioned falsy values where as the second one will fail only if my_variable is None. Normally the variables are initialized with None as a placeholder value and if it is not None at some point of time in the program then they will know that some other value has been assigned to it.

For example,

def print_name(name=None):
    if name is not None:
        print(name)
    else:
        print("Default name")

Here, the function print_name expects one argument. If the user provides it, then it may not be None, so we are printing the actual name passed by the user and if we don't pass anything, by default None will be assigned. Now, we check if name is not None to make sure that we are printing the actual name instead of the Default name.

Note: If you really want to know if your variable is defined or not, you might want to try this

try:
    undefined_variable
except NameError as e:
    # Do whatever you want if the variable is not defined yet in the program.
    print(e)
Sign up to request clarification or add additional context in comments.

Comments

2

No if 0 would be False where if my_variable was actually 0 then if my_variable is not None: would be True, it would be the same for any Falsey values.

In [10]: bool([])
Out[10]: False

In [11]: bool(0)
Out[11]: False

In [12]: bool({})
Out[12]: False
In [13]: [] is not None
Out[13]: True
In [14]: 0 is not None
Out[14]: True

Comments

2

It's worth noting that python variables cannot be uninitialised. Variables in python are created by assignment.

If you want to check for actual uninitialisation, you should check for (non) existence, by catching the NameError exception.

1 Comment

This is more helpful than the accepted answer in cases where the variable is an object. referring to this var in an if statement will fail: uuid_filter: uuid.UUID
0

Taking an example of a null string i.e. '' which is not None

>>> a = ""
>>> if a:
...     print (True)
... 
>>> if a is not None:
...     print (True)
... 
True
>>> 

And a boolean value

>>> a = False
>>> if a:
...     print (True)
... 
>>> if a is not None:
...     print (True)
... 
True
>>> 

Thus they are not equivalent

Comments

0

Check if variable exists is in globals dict, if not initialize variable.

    if 'ots' not in globals():
        ots=0.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.