Home > Article > Backend Development > How Can You Simulate Constants in Python?
Creating Constants in Python
Unlike Java, Python does not natively support the declaration of true constants. However, there are conventions and approaches to simulate constant values in Python code.
Indicating Constants
To convey the intent of a constant to other programmers, a common practice is to name the variable in all uppercase letters:
CONST_NAME = "Name"
Raising Exceptions on Modification
While constants in Python cannot be strictly enforced, it is possible to set up mechanisms to raise exceptions when their values are modified. This can be achieved by utilizing custom decorators, as described in the article "Constants in Python" by Alex Martelli.
typing.Final Annotation
As of Python 3.8, the typing.Final annotation can be used to indicate that a variable should not be reassigned. However, it does not actively prevent reassignment:
from typing import Final a: Final[int] = 1 # MyPy will flag an error: a = 2
This annotation primarily serves as a contract for static type checkers, reminding developers of the intended immutability of the variable.
The above is the detailed content of How Can You Simulate Constants in Python?. For more information, please follow other related articles on the PHP Chinese website!