Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for initialized variable in Python

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?

like image 591
davioooh Avatar asked Jan 15 '15 11:01

davioooh


People also ask

How do you check if a variable has been initialized Python?

Python doesn't have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object.

How do you check for uninitialized variables in Python?

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.

How do you check if a variable is initialized or not?

Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.


3 Answers

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)
like image 123
thefourtheye Avatar answered Oct 06 '22 02:10

thefourtheye


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
like image 41
Padraic Cunningham Avatar answered Oct 06 '22 03:10

Padraic Cunningham


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.

like image 32
Marcin Avatar answered Oct 06 '22 03:10

Marcin