How do I create a constant in Python?
In Python, create a constant by using ALL CAPS for the variable name:
This doesn't enforce the constant's immutability but signifies that MY_CONSTANT
should not be modified.
Emulating constants in Python
Python doesn't natively support constants, but we can emulate them:
Wield typing.Final
From Python 3.8+, you can use typing.Final
to denote that a variable should never be reassigned. This doesn't enforce runtime immutability, but tools like mypy
will catch reassignments.
Opt for OOP
Use classes to house your constants. A clever use of properties can prevent modifications.
Explore __slots__
__slots__
prevents the dynamic creation of attributes in a class, providing a way to emulate immutability:
Experiment with immutable collections
Python offers namedtuple
and Enums
β special types ideal for creating sets of constants:
Constants in disguise
We can disguise variables as constants. Here are some methods:
Sprinkle some decorator magic
A @constant decorator for class properties can make your intent clear and prevent modifications:
Enforce in functions
Create constants using functions to prevent them from being redefined within the scope:
Dive into local scope
Locally, read-only variables can be created using the locals()
function:
Was this article helpful?