Home >Backend Development >Python Tutorial >How to Check for Variable Existence in Python Without Using Exceptions?
In Python, it's common to verify variable existence using try/except blocks:
try: myVar except NameError: # Do something.
However, there are alternative approaches to accomplish this without exceptions.
To check if a local variable exists, use if with locals():
if 'myVar' in locals(): # myVar exists.
Similarly, for global variables, use if with globals():
if 'myVar' in globals(): # myVar exists.
To determine if an object has a specific attribute, use hasattr():
if hasattr(obj, 'attr_name'): # obj.attr_name exists.
The above is the detailed content of How to Check for Variable Existence in Python Without Using Exceptions?. For more information, please follow other related articles on the PHP Chinese website!