How to check if a Python variable exists?

Variables in Python can be defined locally or globally. There are two types of variable first one is local variable that is defined inside the function and the second one are global variable that is defined outside the function.

To check the existence of variable locally we are going to use locals() function to get the dictionary of current local symbol table.

Example:
Examples: Checking local variable existence

filter_none

edit
close

play_arrow

link
brightness_4
code

def func():
  
    # defining local variable
    a_variable = 0
  
    # using locals() function 
    # for checking existence in symbol table
    is_local_var = "a_variable" in locals()
  
    # printing result
    print(is_local_var)
  
# driver code
func()

chevron_right


Output:

True

To check the existence of variable globally we are going to use globals() function to get the dictionary of current global symbol table.



Example:

Examples: Checking global variable existence

filter_none

edit
close

play_arrow

link
brightness_4
code

def func():
  
    # defining variable
    a_variable = 0
  
    # using globals() function check 
    # if global variable exist
    is_global_var = "a_variable" in globals()
  
    # printing result
    print(is_global_var)
  
# driver code
func()

chevron_right


Output:

False

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.