Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

How do I check if a Python variable exists?

I can know if a variable is defined or not using exception handling as follows.

try:
my_variable
except NameError as e:
print str(e)

I want to find if a variable in a python code exists or not without using try-except block.


1 Answer
Rajendra Dharmkar

We use the following code to check if a variable exists in python.

x =10
class foo:
g = 'rt'
def bar(self):
m=6
print (locals())
if 'm' in locals():
print ('m is local variable')
else:
print ('m is not a local variable')
f = foo()
f.bar()
print (globals())
if hasattr(f, 'g'):
print ('g is an attribute')
else:
print ("g is not an attribute")
if 'x' in globals():
print ('x is a global variable')

We get the following output

{'self': <__main__.foo instance at 0x0000000002E24EC8>, 'm': 6}
m is local variable
{'f': <__main__.foo instance at 0x0000000002E24EC8>, '__builtins__': <module '__builtin__' (built-in)>, '__file__': 'C:/Users/TutorialsPoint1/~.py', '__package__': None, 'x': 10, '__name__': '__main__', 'foo': <class __main__.foo at 0x0000000002D29828>, '__doc__': None}
g is an attribute
x is a global variable
Process finished with exit code 0
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.