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.

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.

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.

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.

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:
- Copy a Dictionary in Python
- Check if Python Dictionary is Empty
- Python Dictionary Comprehension
- KeyError in a Nested Python Dictionary

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.