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.
See also  How to send a Whatsapp message with Python?

Leave a Reply

Your email address will not be published.

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