Check initialized variable in Python

I am new to Python and I play a bit with some snippets of code.

In my code, I need to check the variable initialization, and I used this idiom:

if my_variable: # execute some code 

but after reading a few posts, I found this idiom:

 if my_variable is not None: # execute some code 

Are they equivalent or are there some semantic differences?

+5
source share
4 answers

Quoting Python documentation on logical operations ,

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

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

For instance,

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

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

Note. If you really want to know if your variable is defined or not, you can 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) 
+5
source

No if 0 is False, if if my_variable was actually 0 , then if my_variable is not None: True, it will 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 
+2
source

It is worth noting that python variables cannot be uninitialized. Variables in python are created by assignment.

If you want to check for actual uninitialization, you must check for (non) existence by catching a NameError exception.

+1
source

Taking an example of an empty string, i.e. '' which is not None

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

And boolean meaning

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

So they are not equivalent

0
source

Source: https://habr.com/ru/post/1211154/


All Articles