How do I create a constant in Python?

Learn how do i create a constant in python? with practical examples, diagrams, and best practices. Covers python, constants development techniques with visual explanations.

How to Define Constants in Python

Hero image for How do I create a constant in Python?

Explore various strategies for implementing constants in Python, understanding best practices and common pitfalls to write more maintainable and robust code.

Unlike some other programming languages (e.g., C++, Java), Python does not have a built-in const keyword to declare true, immutable constants. This means that by default, any variable can be reassigned. However, developers often need to define values that should not change during program execution to improve code readability, maintainability, and prevent accidental modifications. This article will guide you through the conventional methods and best practices for creating and managing constants in Python.

The Pythonic Way: Naming Conventions

The most widely accepted and Pythonic way to signify a constant is through a naming convention. By convention, variables intended to be constants are named using all uppercase letters with underscores separating words. While this doesn't prevent reassignment, it serves as a strong signal to other developers (and your future self) that the value should be treated as immutable.

PI = 3.14159
GRAVITY = 9.81
MAX_CONNECTIONS = 100

def calculate_circumference(radius):
    return 2 * PI * radius

print(f"Circumference for radius 5: {calculate_circumference(5)}")

# Although not recommended, Python allows reassignment:
# PI = 3.0  # This would be a violation of the constant convention
# print(f"New PI: {PI}")

Defining constants using the all-caps naming convention.

Using a Dedicated Module for Constants

For larger applications, it's common practice to create a separate Python file (e.g., constants.py) to store all global constants. This centralizes constant definitions, making them easier to manage, update, and import across different parts of your project. When importing, you can either import the module directly or import specific constants.

# constants.py

APP_NAME = "My Awesome App"
VERSION = "1.0.0"
DEFAULT_TIMEOUT = 30
ADMIN_EMAIL = "admin@example.com"

# main_app.py

import constants

print(f"Welcome to {constants.APP_NAME} (v{constants.VERSION})")

from constants import DEFAULT_TIMEOUT

print(f"Default timeout is {DEFAULT_TIMEOUT} seconds")

Organizing constants in a dedicated constants.py module.

flowchart TD
    A[Start Application] --> B{Import constants.py}
    B --> C[Access APP_NAME]
    B --> D[Access DEFAULT_TIMEOUT]
    C --> E[Use APP_NAME in UI]
    D --> F[Use DEFAULT_TIMEOUT for network request]
    E & F --> G[Application Logic]
    G --> H[End]

Flow of importing and using constants from a dedicated module.

Enforcing Immutability (Advanced Techniques)

While Python's philosophy relies on developer discipline for constants, there are ways to enforce a degree of immutability, especially for more complex constant structures or when working in teams where strict adherence to conventions might vary. These methods often involve using classes or custom data structures.

class Constants:
    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise TypeError(f"Cannot reassign constant '{name}'")
        self.__dict__[name] = value

    def __delattr__(self, name):
        raise TypeError(f"Cannot delete constant '{name}'")

# Instantiate the constants object
CONFIG = Constants()
CONFIG.DEBUG_MODE = True
CONFIG.DATABASE_URL = "sqlite:///app.db"

print(f"Debug mode: {CONFIG.DEBUG_MODE}")

# Attempting to reassign will raise an error
try:
    CONFIG.DEBUG_MODE = False
except TypeError as e:
    print(f"Error: {e}")

Using a class with __setattr__ to prevent reassignment of constants.