Easy way to check that a variable is defined in python?
Question:
Is there any way to check if a variable (class member or standalone) with specified name is defined? Example:
if "myVar" in myObject.__dict__ : # not an easy way
print myObject.myVar
else
print "not defined"
Answers:
try:
print myObject.myVar
except NameError:
print "not defined"
Paolo is right, there may be something off with the way you’re doing things if this is needed. But if you’re just doing something quick and dirty you probably don’t care about Idiomatic Python anway, then this may be shorter.
try: x
except: print "var doesn't exist"
A compact way:
print myObject.myVar if hasattr(myObject, 'myVar') else 'not defined'
htw’s way is more Pythonic, though.
hasattr()
is different from x in y.__dict__
, though: hasattr()
takes inherited class attributes into account, as well as dynamic ones returned from __getattr__
, whereas y.__dict__
only contains those objects that are attributes of the y
instance.
Read and or tricks in python :
‘a’ in locals() and a
To test if the variable, myvar, is defined:
result = dir().count('myvar')
If myvar is defined, result is 1
, otherwise it would be 0
.
This works fine in Python version 3.1.2.
Is there any way to check if a variable (class member or standalone) with specified name is defined? Example:
if "myVar" in myObject.__dict__ : # not an easy way
print myObject.myVar
else
print "not defined"
try:
print myObject.myVar
except NameError:
print "not defined"
Paolo is right, there may be something off with the way you’re doing things if this is needed. But if you’re just doing something quick and dirty you probably don’t care about Idiomatic Python anway, then this may be shorter.
try: x
except: print "var doesn't exist"
A compact way:
print myObject.myVar if hasattr(myObject, 'myVar') else 'not defined'
htw’s way is more Pythonic, though.
hasattr()
is different from x in y.__dict__
, though: hasattr()
takes inherited class attributes into account, as well as dynamic ones returned from __getattr__
, whereas y.__dict__
only contains those objects that are attributes of the y
instance.
Read and or tricks in python :
‘a’ in locals() and a
To test if the variable, myvar, is defined:
result = dir().count('myvar')
If myvar is defined, result is 1
, otherwise it would be 0
.
This works fine in Python version 3.1.2.