How Can I Create Constants in Python?

Mary-Kate Olsen
Release: 2024-11-20 03:22:02
Original
221 people have browsed it

How Can I Create Constants in Python?

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"
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template