I want to check if a variable exists. Now I'm doing something like this:
try: myVar except NameError: # Do something.
Are there other ways without exceptions?
To check the existence of a local variable: if 'myVar' in locals(): # myVar exists. To check the existence of a global variable: if 'myVar' in globals(): # myVar exists.
Use the typeof operator to check if a variable is defined or initialized, e.g. if (typeof a !== 'undefined') {} . If the the typeof operator doesn't return a string of "undefined" , then the variable is defined.
There is no way in the C++ language to check whether a variable is initialized or not (although class types with constructors will be initialized automatically). Instead, what you need to do is provide constructor(s) that initialize your class to a valid state.
To check the existence of a local variable:
if 'myVar' in locals(): # myVar exists.
To check the existence of a global variable:
if 'myVar' in globals(): # myVar exists.
To check if an object has an attribute:
if hasattr(obj, 'attr_name'): # obj.attr_name exists.
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