

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

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:
Python doesn’t stop you from changing them:
Workarounds for Constants
If you really want to simulate constants, here are two common ways:
Using Class:
You use it like: Constants.PI
, but still it can be changed unless extra protection is added.
Using typing.Final
(Python 3.8+):
Tools like mypy will throw a warning if you try to reassign PI
.
Using Immutable NamedTuples or dataclass(frozen=True):
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.