Skip to content

Check if variable exists in Python

How to check if a variable exists in Python ?

Python doesn’t have a specific function to test whether a variable is defined, since all variables are expected to have been defined before use, even if initially assigned the None object.

The following are the ways to check if variable exists in Python.

Local variable

if 'myVar' in locals():
    # myVar exists.

Global variable

if 'myVar' in globals():
    # myVar exists.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.