You can easily check if a variable exists in Python in either local or global scope.
To check if a variable exists in the global scope, verify the name of the variable as a string between quotes and use the in
operator using the globals()
function.
To check if a variable exists in the local scope, you also verify the name of the variable as a string and check it against the locals()
function.
Paste the code below in exists.py
file and run on your terminal python exists.py
.
my_phrase = 'Hello World'
def prints_the_argument(phrase):
print(phrase)
if "my_phrase" in globals():
print("my_phrase exists globally")
if "my_phrase" in locals():
print("my_phrase exists locally")
if "phrase" in globals():
print("phrase exists globally")
if "phrase" in locals():
print("phrase exists locally")
prints_the_argument('Hello World')
You should see the output below.
Hello World
my_phrase exists globally
phrase exists locally
Notice how my_phrase
is in the global scope, but not in local, while phrase
exists in the local scope, but not in global.
Watch on Youtube
You can also watch this content on Youtube: