In contrast to Java, Python lacks a built-in mechanism for defining constants.
To convey the immutability of a variable, Python programmers typically assign it a name in all uppercase letters:
CONST_NAME = "Name"
Although convention suggests that constants should remain unchanged, there is no inherent protection against their alteration. However, external libraries offer solutions for raising exceptions upon constant modification. Alex Martelli's "Constants in Python" article outlines one such approach, though its use is uncommon.
In Python 3.8, the typing.Final annotation aids static type checkers (e.g., mypy) in recognizing variables that should not be reassigned. Despite its intent, this annotation does not prevent reassignment in runtime:
from typing import Final a: Final[int] = 1 # Executes without error, but mypy will report an error if run: a = 2
The above is the detailed content of How to Define and Protect Constants in Python?. For more information, please follow other related articles on the PHP Chinese website!