Creating Constants in Python
Unlike in Java, where constants are declared using public static final, Python does not have a native concept of constants. However, there are several conventions and approaches for indicating constants to other developers.
Using Uppercase Variables
To signify that a variable should be treated as a constant, the Python community follows the convention of writing variable names in all uppercase.
CONST_NAME = "Name"
Raising Exceptions for Constant Changes
While the uppercase convention is widely recognized, some developers prefer a more strict approach. Constant definitions can be wrapped in a function that raises exceptions when the constant's value is changed, as described in Alex Martelli's article "Constants in Python."
Typing.Final Annotation
In Python 3.8 and later, the typing.Final variable annotation can be used to inform static type checkers that a variable should not be reassigned. However, it's important to note that this is not enforced at runtime and can be overridden.
from typing import Final a: Final[int] = 1
While these approaches provide mechanisms for indicating constants, it's worth emphasizing that constants are not truly immutable in Python. The language allows for reassignments and provides no built-in mechanism for preventing them.
The above is the detailed content of How Can I Create Constants in Python?. For more information, please follow other related articles on the PHP Chinese website!