PythonPython Variables and Data TypesPython variables
What are constants in Python, and how are they represented?
Question 39 of 88 · Updated
On this page
- 1. How do you define a constant in Python?
- 2. Why are constants useful?
- 3. Constant names versus immutable objects
- 4. Using typing.Final to declare intent
- 5. Read-only mappings with MappingProxyType
- 6. Enum for a fixed set of symbolic values
- 7. Frozen dataclasses for grouped settings
- 8. Built-in and standard-library constants
- 9. Choosing the right representation
- 10. Practical example: a named capacity rule
- 11. Common mistakes
- Frequently asked questions
- Does Python have a const keyword?
- What is the difference between Final and an immutable object?
- Are all uppercase variables constants?
- Can a constant be a list?
- Should configuration always be stored in constants?
- Interview-ready answer
- Official references
A constant is a named value that is intended to remain unchanged throughout the relevant part of a program. Python conventionally represents user-defined constants using module-level names written in uppercase with underscores, such as MAX_RETRIES or DEFAULT_TIMEOUT.
Unlike languages with a dedicated constant-declaration keyword, Python does not generally prevent an ordinary name from being reassigned. Developers communicate constant intent through naming, type annotations such as typing.Final and suitable immutable data structures.
1. How do you define a constant in Python?#
PYTHONMAX_RETRIES = 3 print(MAX_RETRIES) MAX_RETRIES = 5 print(MAX_RETRIES)
Output:
3
5The uppercase name follows the PEP 8 naming convention for constants. The second assignment is still legal Python: uppercase spelling does not create a read-only binding.
In real application code, avoid reassigning a constant unless its intended contract has changed. The example deliberately violates the convention to demonstrate the difference between naming intent and runtime enforcement.
Prefer descriptive names that express the purpose and units of a value. For example, TIMEOUT_SECONDS communicates more information than TIMEOUT or the literal 30.
2. Why are constants useful?#
A well-named constant gives a value a clear meaning and keeps related code consistent. For example, MAX_RETRIES can document a retry policy, while SECONDS_PER_MINUTE can identify a fixed unit conversion.
Constants help with:
- Readability: replace unexplained numeric or string literals with meaningful names.
- Maintenance: keep a shared policy value in one appropriate location.
- Consistency: reduce accidental differences between code paths implementing the same rule.
- Communication: signal that callers should not change a particular setting.
Not every literal needs a named constant. A simple expression such as count + 1 is often clearer than introducing a constant for the number one. Use a name when it communicates domain meaning or centralizes an actual shared rule.
3. Constant names versus immutable objects#
The distinction between a name and the object it refers to matters.
| Concept | Meaning | Example |
|---|---|---|
| Constant naming convention | Indicates a binding is intended to remain stable | MAX_RETRIES = 3 |
| Immutable object | Its value cannot be modified in place | An integer, string or tuple |
| Final annotation | Tells a static type checker that a name should not be reassigned | LIMIT: Final[int] = 5 |
| Runtime read-only interface | Rejects particular mutations or assignments through an interface | MappingProxyType or a frozen dataclass |
An uppercase name can refer to a mutable list or dictionary, and an immutable object can be referenced by a name that is later reassigned. These properties are independent.
For a deeper explanation of shared references, see the preceding mutable-versus-immutable and multiple-assignment lessons.
4. Using typing.Final to declare intent#
Python 3.8 introduced typing.Final as part of its support for static typing. A Final annotation expresses that a name should not be reassigned after initialization.
PYTHONfrom typing import Final TIMEOUT: Final[int] = 10 TIMEOUT = 20 print(TIMEOUT)
Output when executed by ordinary Python:
20A static type checker following the Final contract should report the second assignment as an error. The Python interpreter does not automatically enforce that restriction at runtime.
In application code, declare the intended value once and avoid the reassignment shown in this demonstration. Run a suitable type checker in your development and CI workflow when you want static enforcement.
You can use Final without an explicit inner type when inference is appropriate, or use Final[int] when the intended type should be stated explicitly. Final does not make the referred-to object immutable.
PYTHONfrom typing import Final ALLOWED: Final[list[str]] = ["read"] ALLOWED.append("write") print(ALLOWED)
Output:
['read', 'write']The binding is intended to remain unchanged, but the list remains mutable. Appending an item does not rebind ALLOWED.
If the permitted values must not change, choose an immutable representation, such as a tuple of strings or a frozenset, according to whether order and duplicate handling matter.
The example uses the built-in generic list[str] notation supported from Python 3.9. Final itself is available from Python 3.8; older supported typing environments may use a suitable alternative annotation syntax.
5. Read-only mappings with MappingProxyType#
A read-only mapping interface can be useful when other code should be able to inspect a dictionary without modifying it through that interface.
PYTHONfrom types import MappingProxyType source = {"limit": 3} LIMITS = MappingProxyType(source) print(LIMITS["limit"]) source["limit"] = 5 print(LIMITS["limit"])
Output:
3
5MappingProxyType exposes a read-only view of the underlying mapping. Assigning through the proxy, such as LIMITS["limit"] = 7, raises TypeError. However, another reference to the underlying dictionary can still modify it, and the view reflects those changes.
A read-only view is therefore not necessarily an immutable snapshot. Nested mutable objects can also be changed through references retrieved from the mapping. Keep ownership and sharing rules clear if configuration stability matters.
6. Enum for a fixed set of symbolic values#
Use an enumeration when a domain contains a defined set of alternatives, such as order states or job statuses.
PYTHONfrom enum import Enum class Status(Enum): PENDING = "pending" DONE = "done" print(Status.DONE.name, Status.DONE.value) print(Status("done") is Status.DONE)
Output:
DONE done
TrueAn Enum defines named members with associated values. The class provides a structured representation of the allowed choices rather than scattering unrelated strings throughout the program.
Reassigning an existing enumeration member through its class, such as Status.DONE = "other", raises AttributeError. This does not make every possible member value deeply immutable: an enumeration can contain mutable values, although immutable scalar values are often easier to reason about.
Enum is a good fit for symbolic states. It is not necessary merely to define a single unrelated number such as DEFAULT_PAGE_SIZE.
7. Frozen dataclasses for grouped settings#
When a group of related values should resist ordinary field reassignment, a frozen dataclass can provide a convenient interface.
PYTHONfrom dataclasses import dataclass @dataclass(frozen=True) class Policy: max_retries: int = 3 timeout_seconds: int = 10 print(Policy())
Output:
Policy(max_retries=3, timeout_seconds=10)Ordinary field assignment on an instance, such as policy.max_retries = 4, raises FrozenInstanceError, a subclass of AttributeError.
A frozen dataclass emulates read-only fields; it is not a deep-freezing mechanism or a security boundary. Nested mutable field values can still be changed, and advanced runtime mechanisms can bypass normal assignment restrictions.
Use immutable field values and a clear ownership model if the grouped settings must remain stable.
8. Built-in and standard-library constants#
Python also supplies predefined values. None, True and False are language-defined special values whose keywords cannot be assigned to. Their behavior differs from ordinary uppercase names.
The standard library provides mathematical constants such as math.pi and math.e. Those are module attributes containing numerical values, not exact symbolic representations of the underlying mathematical constants.
PYTHONfrom math import pi, isclose print(isclose(pi * 2, 6.283185307179586)) print(None is None)
Output:
True
TrueThe math.pi value is a floating-point approximation of pi. The None identity comparison illustrates the singleton semantics discussed earlier in the NoneType lesson.
The assignment None = 1 is invalid Python syntax. This is a language restriction, unlike the convention that discourages reassigning MAX_RETRIES.
9. Choosing the right representation#
These techniques can be combined. For example, a Final name can refer to a tuple of immutable strings. The annotation concerns the name's reassignment contract, while the tuple provides runtime immutability of its positions.
The diagram describes typical choices, not interchangeable levels of security. None of the ordinary user-defined techniques makes arbitrary Python code tamper-proof.
10. Practical example: a named capacity rule#
PYTHONfrom typing import Final MAX_ITEMS: Final[int] = 5 def can_add(current_count: int) -> bool: return 0 <= current_count < MAX_ITEMS print(can_add(4), can_add(5), can_add(-1))
Output:
True False FalseThe named constant makes the capacity limit explicit, and the function rejects a negative count. The example assumes an integer input and does not validate the runtime input type.
For bounded-size integers, this decision uses a constant number of comparisons and constant auxiliary storage. With arbitrary-precision operands, the actual comparison cost can depend on their sizes.
If the limit varies by tenant, environment or customer plan, it is better represented by validated configuration or a function parameter than by a universal module-level constant. A real capacity reservation system also needs an atomic check-and-update mechanism to prevent concurrent requests from exceeding the limit.
11. Common mistakes#
| Mistake | Better approach |
|---|---|
| Assuming uppercase names cannot be reassigned | Treat uppercase spelling as a convention |
| Assuming Final enforces runtime immutability | Use a type checker and choose an appropriate value representation |
| Storing mutable nested objects in a supposedly immutable collection | Review the mutability of referenced elements |
| Treating a mapping proxy as a snapshot | Remember that underlying changes can remain visible |
| Using constants for secrets or deployment-specific settings | Load validated configuration and secrets through appropriate mechanisms |
| Replacing all ordinary literals with names | Name values when the name adds meaningful context |
Keep constants near the domain logic that owns them. A dedicated constants or configuration module can be useful for genuinely shared values, but an unrelated global collection of every literal can make dependencies harder to understand.
Frequently asked questions#
Does Python have a const keyword?#
No. Ordinary user-defined constants use naming conventions, optional static typing and suitable runtime representations.
What is the difference between Final and an immutable object?#
Final expresses that a binding should not be reassigned. Immutability means that an object's value cannot be modified in place. A Final name can still refer to a mutable object.
Are all uppercase variables constants?#
No. Uppercase spelling expresses convention; Python does not infer a constant declaration from capitalization.
Can a constant be a list?#
Yes, but the list remains mutable. If its contents must remain stable, choose an appropriate immutable representation and consider nested objects.
Should configuration always be stored in constants?#
No. Values that vary across deployments, users or runtime conditions belong in a suitable configuration system or parameter. Do not hardcode secrets.
Interview-ready answer#
Constants in Python are names whose values are intended to remain unchanged. By convention, they are written in uppercase with underscores, such as MAX_RETRIES = 3. Python does not provide a general const keyword or enforce this naming convention at runtime. The typing.Final annotation allows static type checkers to detect reassignment, but it does not freeze the referenced object. Immutable values, enums, frozen dataclasses and read-only mapping interfaces can be used depending on the required behavior. The key distinction is between keeping a name's binding stable and preventing changes to the object itself.
Official references#
- PEP 8 — Constants
- Python Standard Library — typing.Final
- PEP 591 — Adding a final qualifier to typing
- Python Standard Library — types.MappingProxyType
- Python Standard Library — enum
- Python Standard Library — dataclasses
- Python Standard Library — Built-in Constants
- Python Standard Library — math constants
Verification note: Eight runnable output examples and four independent expected-exception tests passed on CPython 3.13.5, including reassignment of ordinary and Final-annotated names, mutation through a Final binding, mapping-proxy behavior, Enum lookup and member reassignment, frozen dataclass behavior and invalid assignment to None. No local mypy or pyright installation was found; static checker diagnostics were not executed. The fenced Mermaid diagram was manually reviewed; no local Mermaid CLI was found. Official links are supplied under the authorized offline research exception; live documentation, Supabase changelog and public-site rendering were not checked.
References
- 1.PEP 8 — Constantspeps.python.org
- 2.Python Standard Library — typing.Finaldocs.python.org
- 3.PEP 591 — Adding a final qualifier to typingpeps.python.org
- 4.Python Standard Library — types.MappingProxyTypedocs.python.org
- 5.Python Standard Library — enumdocs.python.org
- 6.Python Standard Library — dataclassesdocs.python.org
- 7.Python Standard Library — Built-in Constantsdocs.python.org
- 8.Python Standard Library — math constantsdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design