Determine if variable is defined in Python

Question:

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?
Asked By: user102008

||

Answers:

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope
Answered By: sc45
try:
    thevariable
except NameError:
    print("well, it WASN'T defined after all!")
else:
    print("sure, it was defined.")
Answered By: Alex Martelli

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

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

Answered By: John La Rooy

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

a = None
if condition:
    a = 42
Answered By: divegeek

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.

Answered By: Denis Otkidach

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.

Answered By: xsreality
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.