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 wayprint myObject.myVar
elseprint "not defined"
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 wayprint myObject.myVar
elseprint "not defined"
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.