Determine if variable is defined in Python


Question

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?
1
368
5/23/2017 12:26:36 PM

Accepted Answer

try:
  thevariable
except NameError:
  print "well, it WASN'T defined after all!"
else:
  print "sure, it was defined."
575
2/17/2015 4:36:17 PM

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

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon