Check if a Variable Is Defined in Python

In my years working as a Python Keras developer, I’ve often needed to check if a variable is defined before using it. This simple check helps avoid runtime errors and makes your code more resilient.

In this article, I’ll walk you through practical methods to check if a variable is defined in Python. Each method comes with clear explanations and full code examples you can use immediately in your Python Keras projects.

Method 1: Use try-except to Check if a Variable Is Defined in Python Keras Code

The most direct way to check if a variable is defined is by trying to access it inside a try block and catching a NameError if it’s not defined. This method is easy and works well in all Python environments.

try:
    print(model)
except NameError:
    print("Variable 'model' is not defined.")
else:
    print("Variable 'model' is defined.")

You can see the output in the screenshot below.

python check if variable is defined

This approach catches the error when model is not defined and avoids your program crashing unexpectedly.

Method 2: Check Variable Existence Using globals() in Python Keras Scripts

You can check if a variable exists in the global scope by using the globals() dictionary. This method is useful when you want to inspect variables defined at the module level.

if 'model' in globals():
    print("Variable 'model' is defined in global scope.")
else:
    print("Variable 'model' is not defined in global scope.")

You can see the output in the screenshot below.

python check if variable exists

This method returns True only if the variable exists globally, which can help in managing Keras model objects or data variables.

Method 3: Use locals() to Check for Variable Definition Inside Functions

When working inside functions, locals() gives you access to the local symbol table. You can use it to check if a variable is defined within the current function’s scope.

def check_variable():
    model = "Keras Model"
    if 'model' in locals():
        print("Variable 'model' is defined locally.")
    else:
        print("Variable 'model' is not defined locally.")

check_variable()

You can see the output in the screenshot below.

python check if a variable is defined

This method is handy when you want to verify local variables before using them in your Keras training functions.

Method 4: Use vars() for Object Attribute Checks in Python Keras Projects

If you want to check if an object has a specific attribute (like a layer or parameter in a Keras model), vars() can help by returning the __dict__ attribute of the object.

class MyModel:
    def __init__(self):
        self.layer1 = "Dense Layer"

model = MyModel()

if 'layer1' in vars(model):
    print("Attribute 'layer1' is defined in model.")
else:
    print("Attribute 'layer1' is not defined in model.")

You can see the output in the screenshot below.

python is variable defined

This method is useful when inspecting Keras model components dynamically.

Method 5: Use hasattr() to Check Attributes in Python Keras Objects

hasattr() is a built-in function designed to check if an object has a given attribute. It’s the most Pythonic way to verify attributes in Keras model instances.

class MyModel:
    def __init__(self):
        self.optimizer = "adam"

model = MyModel()

if hasattr(model, 'optimizer'):
    print("Model has 'optimizer' attribute.")
else:
    print("Model does not have 'optimizer' attribute.")

This method is clean and efficient for checking model properties or configurations.

Practical Example: Check Variables When Building a Keras Model

When building a Keras model, you might want to verify if a variable like input_shape or model exists before proceeding.

try:
    input_shape
except NameError:
    input_shape = (28, 28, 1)
    print("Variable 'input_shape' was not defined. Setting default:", input_shape)

if 'model' not in globals():
    from tensorflow.keras.models import Sequential
    from tensorflow.keras.layers import Dense, Flatten

    model = Sequential([
        Flatten(input_shape=input_shape),
        Dense(128, activation='relu'),
        Dense(10, activation='softmax')
    ])
    print("Keras model created.")
else:
    print("Keras model already defined.")

This snippet avoids errors by checking variable definitions and setting defaults when necessary.

Checking if a variable is defined in Python is a small but vital step in writing robust Keras code. These methods help you prevent crashes and manage your model and data variables effectively.

By using these methods, you’ll write Python Keras code that handles variable definitions gracefully and avoids common pitfalls. Keep practicing these checks to build more reliable machine learning pipelines.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.