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"
To check if the variable is defined in a local scope, you can use the locals() function, which returns a dictionary representing the current local symbol table. if 'x' in locals(): print('Variable exist. ')
To get the type of a variable in Python, you can use the built-in type() function. In Python, everything is an object. So, when you use the type() function to print the type of the value stored in a variable to the console, it returns the class type of the object.
To check if a global variable exists in Python, use the in operator against the output of globals() function, which has a dictionary of a current global variables table. The “in operator” returns a boolean value. If a variable exists, it returns True otherwise False.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With