Declaring Constants in Python
Unlike Java, where constants are declared with the final keyword, Python does not natively support constants. However, certain practices have emerged to simulate constants in Python.
Simulating Constants with UPPERCASE Names:
To indicate that a variable is intended as a constant, it is commonly written in uppercase letters:
CONST_NAME = "Name"
Exception-Raising Constants:
To raise exceptions when a constant is modified, a more complex approach using custom classes and decorators is suggested in Alex Martelli's article "Constants in Python."
Typing.Final Variable Annotation (Python 3.8 ):
In Python 3.8 and later, a typing.Final variable annotation can be used to indicate to static type checkers that a variable should not be reassigned. However, it does not prevent reassignment at runtime:
from typing import Final a: Final[int] = 1 a = 2 # Executes without error, but mypy will issue an error.
Note:
While these practices can help maintain the intended immutability of constants, they do not strictly enforce it. Redefining constants remains possible but is discouraged.
The above is the detailed content of How Can I Simulate Constants in Python?. For more information, please follow other related articles on the PHP Chinese website!