LANGUAGE/Python
How to check whether a variable exists or not?
Hogeony
2019. 8. 1. 12:13
To check the existence of a local variable:
myVar = 10
if 'myVar' in locals():
print(myVar)
else:
print('None')
if 'myNum' in locals():
print(myNum)
else:
print('None')
To check the existence of a global variable:
myVar = 10
if 'myVar' in globals(): print(myVar)
else: print('None')
if 'myNum' in globals(): print(myNum)
else: print('None')
To check if an object has an attribute:
if hasattr(obj, 'attr\_name'): print(obj)
else: print('None')
#References
https://stackoverflow.com/questions/843277/how-do-i-check-if-a-variable-exists