Skip to content

How to create a constant in Python

Learn how to create constant, read-only variables in Python.


Learn how to create constant, read-only variables in Python.

Many other languages like C++ or Java have keywords to declare constants:

C++
const int maxValue = 99;
Java
public static final int MAX_VALUE = 99;

But what about a constant specifier in Python?

Constants in Python

In Python, we cannot declare a variable or value as constant in Python.

But we can indicate to programmers that a variable is a constant by using an all upper case variable name.

This is the common practice to create a constant in Python:

MAX_VALUE = 99

Even though we can change the value, it is then the programmer's responsibility to leave this variable unchanged.

typing.Final in Python

Since Python 3.8, there is a Final specifier in the typing module.

With type hints, the code still runs fine but type checkers like mypy can report errors when they are applied to the code:

from typing import Final

MAX_VALUE: Final[int] = 99

# This executes fine, but mypy will report an error if mypy is applied:
MAX_VALUE = 100

Use a namedtuple for constant values

If you really want to enforce read-only variables, you can use a namedtuple. namedtuples are easy to create, lightweight object types. Since they are a subclass of regular tuples, they are immutable:

from collections import namedtuple
Constants = namedtuple('Constants', ['pi', 'max_value'])

constants = Constants(3.14, 99)
print(constants.pi) # 3.14
print(constants.max_value) # 99

constants.max_value = 100
# Traceback (most recent call last):
#   File "<stdin>", line 5, in <module>
# AttributeError: can't set attribute

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*


Python Problem-Solving Bootcamp

🚀 Solve 42 programming puzzles over the course of 21 days: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏