Python Constants
By Flavio Copes
Python has no true constants, but you can get close with an Enum that nobody can reassign, or just follow the convention of naming a variable in uppercase.
Python has no way to enforce a variable to be a constant. There’s no const keyword like in JavaScript. What we have is a naming convention, plus a couple of tricks that get closer to real constants.
The convention: uppercase names
Declare variables that should never change using uppercase names:
WIDTH = 1024
MAX_RETRIES = 5
No one will prevent you from overwriting these values, and Python will not stop it. But every Python developer reading your code knows what the uppercase means: don’t touch this.
That’s what most Python code you will see does. Constants usually sit at the top of a module, or in a dedicated module like config.py that other files import from.
Enforcing it with an Enum
If you want actual protection, the nearest you can go is to use an enum:
from enum import Enum
class Constants(Enum):
WIDTH = 1024
HEIGHT = 256
You get to each value using the value attribute:
print(Constants.WIDTH.value) # 1024
No one can reassign that value. Python raises an error if you try:
Constants.WIDTH = 5
# AttributeError: cannot reassign member 'WIDTH'
The tradeoff is the extra .value everywhere, and forgetting it is the classic mistake. Constants.WIDTH is the enum member, not the number, so this fails:
Constants.WIDTH * 2
# TypeError: unsupported operand type(s) for *: 'Constants' and 'int'
The fix is Constants.WIDTH.value * 2. If you find yourself writing .value all the time, the plain uppercase convention might serve you better.
Marking constants with Final
Python 3.8 added Final to the typing module:
from typing import Final
TIMEOUT: Final = 30
At runtime this changes nothing. You can still reassign TIMEOUT and Python won’t complain. But a type checker like mypy flags the reassignment as an error, so you catch it before the code runs.
If your project already runs a type checker, this is the cleanest option: normal variables, normal syntax, and the mistake gets caught anyway.
Related posts about python: