Meaning
Defines a named constant that cannot be reassigned, providing type safety and clarity through explicit type annotation. This addresses the pain point of magic numbers and the risk of accidental modification of values that should remain fixed. It is used when a value must remain constant throughout the program's execution, particularly when the same value is used in multiple locations to ensure consistency and prevent unintended changes.
Primary Function
Constant Declaration
Communicative Purpose
Prevents magic numbers and unintended reassignment of fixed values.
Pattern
constant_name: Final[type] = value
Core Structure
constant_name: Final[...] = ...
Função primária
Constant Declaration
Propósito comunicativo
Prevents magic numbers and unintended reassignment of fixed values.
Situações de gatilho
Software configuration: defining application-wide settings like maximum buffer sizes or timeouts; Mathematical constants: declaring values such as pi or conversion factors that should not change; Game development: setting fixed values like screen dimensions or frame rate limits.
Contextos
Python applications requiring type safety and immutability, configuration modules, mathematical libraries, game engines
Padrão
constant_name: Final[type] = value
Estrutura central
constant_name: Final[...] = ...
Slots de substituição
constant_name: descriptive identifier for the constant (e.g., MAX_SIZE, PI), type: the data type of the constant (e.g., int, str, float), value: the assigned value matching the type (e.g., 1024, 3.14, 'utf-8')
Colocados típicos
- type hints
- configuration files
- enum classes
- constant modules
Substituições comuns
- using a regular variable (risk of reassignment)
- using a global variable without Final (no immutability guarantee)
- using a class attribute (less accessible)
Erros comuns
forgetting to import Final from typing_extensions (for Python <3.8) -> NameError; assigning a mutable object (e.g., list) and modifying its contents -> unexpected state changes; using Final on a class attribute without understanding it only prevents reassignment of the attribute itself, not mutation of mutable values
Similar / contraste
typing.Literal: specifies exact values a variable can hold rather than immutability; const in other languages: similar concept but syntax varies (e.g., JavaScript const, C++ const); enum: defines a set of related named constants
Interferências
Coming from Java: may use public static final -> Python's Final is module-level and doesn't require class wrapping; Coming from C: may use #define macros -> lacks type safety and doesn't integrate with type checkers; Coming from JavaScript: may use const -> similar behavior but Python's Final is primarily for type checkers and doesn't enforce immutability at runtime
Família do chunk
- constant definition
- type hint
- immutable data
Nuance
Do not use for values that need to be recalculated or changed based on context; runtime immutability is not enforced by Final (only type checkers like mypy), so mutable objects assigned to Final constants can still be modified internally; the value must be a compile-time constant for full benefit
Efeito pragmático
Enables static type checkers to detect reassignment attempts, improves code readability by giving meaningful names to fixed values, and prevents bugs from accidental modification of configuration values
Dica de memória
Final constants are like sealed envelopes: once you write the value inside and seal it, you can't change what's written without breaking the seal.
Upgrade path
Using dataclasses.frozen=True for immutable objects or exploring Python's typing.Literal for exact value constraints
Log in to save chunks.