How can I check if a Python variable exists?

Python Methods and Functions

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





Example < / h2>
 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') 



Output

We get the following output

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







Get Solution for free from DataCamp guru