Python - Constant is a myth. We all are adults here

Vaibhav Singh
Posted on 9th Jun 2025 6:30 PM | 10 min Read | 60 min Implementation

#python #constant #vaibhav #define-constant #constantinpython

We will start our discussion today with a very simple statement


Python does not have any built-in mechanism for defining constants.


Many of my students ask this question:


"In Java, JavaScript, Go, C#, C++, and many other languages, we have built-in support for constants — but why not in Python?"


I’ve explored the official documentation thoroughly, but unfortunately, there’s no clear or direct explanation. However, based on insights from various forums and my own understanding, I’ve come up with some reasons and workarounds, which I’ll share below.



Python's Philosophy: "We Are All Adults Here"


Python follows the principle of:

"We're all consenting adults here."

This means it assumes the programmer is responsible enough to not change a value if it is meant to be constant, rather than enforcing it via the language syntax.



Dynamic Typing and Flexibility


Python is a dynamically typed and interpreted language, which gives you a lot of flexibility. Constants would go against that flexibility unless explicitly handled via convention or third-party tools.



Convention Over Enforcement


By convention, constants are named using ALL_CAPS:

PI = 3.14159
MAX_USERS = 100


Python doesn’t stop you from changing them:

PI = 3# Allowed, but discouraged





Workarounds for Constants


If you really want to simulate constants, here are two common ways:


Using Class:

class Constants:
PI = 3.14159
MAX_USERS = 100


You use it like: Constants.PI, but still it can be changed unless extra protection is added.



Using typing.Final (Python 3.8+):

from typing import Final

PI: Final = 3.14159

Tools like mypy will throw a warning if you try to reassign PI.



Using Immutable NamedTuples or dataclass(frozen=True):

from dataclasses import dataclass

@dataclass(frozen=True)
classConstants:
PI: float = 3.14159
MAX_USERS: int = 100

const = Constants()
# const.PI = 3.14 # This will raise a FrozenInstanceError





While Python doesn't enforce constants at the language level, developers can still achieve constant-like behavior through conventions (ALL_CAPS), type hints using typing.Final, or by using immutable data structures like @dataclass(frozen=True). This flexibility aligns with Python's philosophy of trusting the developer's intent over rigid enforcement. Ultimately, it's less about restriction and more about responsibility—Python empowers you to write clean, maintainable code by choice, not by force.

All Comments ()
Do You want to add Comment in this Blog? Please Login ?