debugpythonCriticalCanonical
How do I check if a variable exists?
Viewed 0 times
checkexistshowvariable
Problem
I want to check if a variable exists. Now I'm doing something like this:
Are there other ways without exceptions?
try:
myVar
except NameError:
# Do something.Are there other ways without exceptions?
Solution
To check the existence of a local variable:
To check the existence of a global variable:
To check if an object has an attribute:
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.Code Snippets
if 'myVar' in locals():
# myVar exists.if 'myVar' in globals():
# myVar exists.if hasattr(obj, 'attr_name'):
# obj.attr_name exists.Context
Stack Overflow Q#843277, score: 2373
Revisions (0)
No revisions yet.