How to Define Truly Immutable Constants in Python

At first, this question might sound contradictory—after all, isn’t the whole point of a constant that its value doesn’t change?

In theory, yes. But in practice, things are a bit different. Python doesn’t have a built-in way to define constants. Instead, by convention, we assign a value to a regular variable and write its name in all uppercase letters to indicate that it should not be modified. However, this is just a naming convention, not actual protection. Python won’t stop anyone from reassigning the value.

But that doesn’t mean we have to accept it. If you’re worried about constants being changed—accidentally or otherwise—there are several ways to make them effectively immutable in Python.

Here are three approaches:

1. Using namedtuple fields

This approach uses a namedtuple, where each field represents a constant. The defaults argument sets their values.

This example also shows that a constant can be referenced using different names. You can even use Greek letters commonly used in mathematics (such as π), since Python allows identifiers to contain Unicode characters. (This topic was discussed in a previous post.)

2. Defining Constants as Read-Only Properties in a Class

Here, constants are defined as read-only properties inside a class. Any attempt to overwrite them raises an error.

3. Using a dataclass with frozen=True

In this solution, constants are defined as fields of a dataclass that is marked as frozen, which makes all attributes read-only after instantiation.

All language elements used in these three approaches are explained in more detail—with examples—in the e-book Python Knowledge Building Step by Step.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?