Python Variables – Check if a local variable exists

In this post we will be creating a Python script that will check if a local variable exists, to do this we will be making use of Python’s inbuilt ‘locals()’ function which returns a dictionary representing the current local variables.

See the snippet of code below as an example, here we have two functions where we declare a variable in ‘Function1’ only. We then check if the local variable exists in each of the functions.

def Function1():
    String1="Hello World!"
    if 'String1' in locals():
        print("Function1 - Variable Exists")

def Function2():
    if 'String1' in locals():
        print("Function2 - Variable Exists")

The above would return the following, ‘Function2’ in this example does not print any output as the local variable is not present in this function.

Function1 - Variable Exists

Leave a Reply