Check if a variable is defined in Python
This post will discuss how to check if a variable is defined in Python.
1. Using locals() function
To check if the variable is defined in a local scope, you can use the locals() function, which returns a dictionary representing the current local symbol table.
|
1 2 3 4 5 6 7 8 9 10 11 |
def foo(): x = 2 if 'x' in locals(): print('Variable exist.') else: print('Variable don\'t exist.') if __name__ == '__main__': foo() # Variable exist. |
2. Using vars() function
Alternatively, you can use no-arg vars() function, which acts like locals() function.
|
1 2 3 4 5 6 7 8 9 10 11 |
def foo(): x = 2 if 'x' in vars(): print('Variable exist.') else: print('Variable don\'t exist.') if __name__ == '__main__': foo() # Variable exist. |
3. Using dir() function
Without arguments, the dir() function returns the list of names in the current local scope.
|
1 2 3 4 5 6 7 8 9 10 11 |
def foo(): x = 2 if 'x' in dir(): print('Variable exist.') else: print('Variable don\'t exist.') if __name__ == '__main__': foo() # Variable exist. |
4. Using globals() function
Finally, to check for the existence of a global variable, you can use the globals() function. It returns a dictionary representing the current global symbol table.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
def foo(): if 'x' in globals(): print('Variable exist.') else: print('Variable don\'t exist.') if __name__ == '__main__': x = 2 foo() # Variable exist. |
That’s all about determining whether a variable is defined in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)