Possible Duplicate:
Easy way to check that variable is defined in python?
How do I check if a variable exists in Python?
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?
'a' in vars() or 'a' in globals()
if you want to be pedantic, you can check the builtins too
'a' in vars(__builtins__)
For this particular case it's better to do
a = None
instead ofdel a
. This will decrement reference count to objecta
was (if any) assigned to and won't fail whena
is not defined. Note, thatdel
statement doesn't call destructor of an object directly, but unbind it from variable. Destructor of object is called when reference count became zero.If one wants to catch attempts to access a not-defined variable inside an object, there is a very easy way of doing that:
Here, python first tries to find an attribute within the object or the object tree, and only if that fails the
__getattr__(self, key)
function is called. This means, if__getattr__
is called we can simply returnNone
.I think it's better to avoid the situation. It's cleaner and clearer to write:
One possible situation where this might be needed:
If you are using
finally
block to close connections but in thetry
block, the program exits withsys.exit()
before the connection is defined. In this case, thefinally
block will be called and the connection closing statement will fail since no connection was created.