Determine if variable is defined in Python

PythonVariablesDefined

Python Problem Overview


How do you know whether a variable has been set at a particular place in the code at runtime? This is not always obvious because (1) the variable could be conditionally set, and (2) the variable could be conditionally deleted. I'm looking for something like defined() in Perl or isset() in PHP or defined? in Ruby.

if condition:
    a = 42

# is "a" defined here?

if other_condition:
    del a

# is "a" defined here?

Python Solutions


Solution 1 - Python

try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")

Solution 2 - Python

'a' in vars() or 'a' in globals()

if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)

Solution 3 - Python

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42

Solution 4 - Python

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

Solution 5 - Python

For this particular case it's better to do a = None instead of del a. This will decrement reference count to object a was (if any) assigned to and won't fail when a is not defined. Note, that del statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.

Solution 6 - Python

One possible situation where this might be needed:

If you are using finally block to close connections but in the try block, the program exits with sys.exit() before the connection is defined. In this case, the finally block will be called and the connection closing statement will fail since no connection was created.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser102008View Question on Stackoverflow
Solution 1 - PythonAlex MartelliView Answer on Stackoverflow
Solution 2 - PythonJohn La RooyView Answer on Stackoverflow
Solution 3 - PythondivegeekView Answer on Stackoverflow
Solution 4 - Pythonsc45View Answer on Stackoverflow
Solution 5 - PythonDenis OtkidachView Answer on Stackoverflow
Solution 6 - PythonxsrealityView Answer on Stackoverflow