Python Variables – Check if a global variable exists

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

See the snippet of code below as an example where we check for a global variable within a function.

global String1
String1="Hello World!"

def Function1():    
    if 'String1' in globals():
        print("Function1 - Variable Exists")

The above would return the following as output.

Function1 - Variable Exists

Leave a Reply