
Type-Annotating Constants
January 19, 2025About 1 min
Type-Annotating Constants 관련

Python Constants: Improve Your Code's Maintainability
In this tutorial, you'll learn how to properly define constants in Python. By coding a bunch of practical example, you'll also learn how Python constants can improve your code's readability, reusability, and maintainability.

Python Constants: Improve Your Code's Maintainability
In this tutorial, you'll learn how to properly define constants in Python. By coding a bunch of practical example, you'll also learn how Python constants can improve your code's readability, reusability, and maintainability.
Since Python 3.8, the typing
module includes a Final
class that allows you to type-annotate constants. If you use this class when defining your constants, then you’ll tell static type checkers like mypy that your constants shouldn’t be reassigned. This way, the type checker can help you detect unauthorized assignments on your constants.
Here are some examples of using Final
to define your constants:
from typing import Final
MAX_SPEED: Final[int] = 300
DEFAULT_COLOR: Final[str] = "\033[1;34m"
ALLOWED_BUILTINS: Final[tuple[str, ...]] = ("sum", "max", "min", "abs")
# Later in your code...
MAX_SPEED = 450 # Cannot assign to final name "MAX_SPEED" mypy(error)
The Final
class represents a special typing construct that indicates type checkers to report an error if the name at hand is reassigned at some point in your code. Note that even though you get a type checker’s error report, Python does change the value of MAX_SPEED
. So, Final
doesn’t prevent accidental constant reassignments at runtime.