Home > Backend Development > Python Tutorial > How to Define and Protect Constants in Python?

How to Define and Protect Constants in Python?

Susan Sarandon
Release: 2024-11-28 12:11:12
Original
423 people have browsed it

How to Define and Protect Constants in Python?

Declaring Constants in Python

In contrast to Java, Python lacks a built-in mechanism for defining constants.

Convention for Indicating Constants

To convey the immutability of a variable, Python programmers typically assign it a name in all uppercase letters:

CONST_NAME = "Name"
Copy after login

Preventing Constant Modification

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.

typing.Final Annotation (Python 3.8 )

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

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!

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