Constants in Python

Learn how Python developers create constants using uppercase naming, why Python has no const keyword, and how to write code that signals read-only values.

5 min read

Python constants are a convention-driven feature. Unlike languages that provide a dedicated keyword to lock a value from being reassigned, Python relies on a naming pattern that every developer in the community recognizes and respects. If you have worked through the article on Python variables, you already know that Python variable names signal intent through their casing. Constants take that idea one step further by using uppercase letters exclusively, which instantly tells any reader that this value is meant to stay the same for the entire lifetime of the program.

The number of seconds in a minute, the default port for a web server, the maximum login attempts before an account is locked: these are all values that should never change while a program runs. Python does not stop you from changing them, but it gives you a clear, universal way to mark them so that nobody on your team (including your future self) accidentally treats them as mutable state.

The UPPER_CASE naming convention

PEP 8, Python's official style guide, states that constants should be written in all capital letters with underscores separating words. This rule has governed Python code since PEP 8 was first published, and it is followed so consistently that any developer seeing MAX_RETRIES = 5 at the top of a file immediately understands it is a fixed value, not something that changes during execution. This uppercase rule is one part of a broader set of Python variable naming rules worth reviewing if casing conventions are still new to you.

Here is how constants typically appear in a module, placed right after the import block and before any function or class definitions:

pythonpython
import os
 
MAX_CONNECTIONS = 100
DEFAULT_TIMEOUT = 30
DATABASE_HOST = "localhost"
PI = 3.1415926535

Every name in that block uses uppercase, which tells readers that these are configuration or fixed parameters rather than runtime state. Python itself treats these names exactly the same as any other variable; the interpreter does not enforce read-only behavior. But any developer who reassigns one of these names in production code is violating a social contract that the entire Python community observes. If you are working on a team, a code reviewer will flag that reassignment immediately.

When a constant is only relevant inside a single class, define it as a class attribute at the top of the class body, still using uppercase:

pythonpython
class RateLimiter:
    MAX_REQUESTS = 60
    COOLDOWN_SECONDS = 5
 
    def __init__(self):
        self.count = 0

This keeps the constant scoped to where it is used while still making its read-only intent clear through the naming convention.

Why Python trusts convention over enforcement

Python's design philosophy favors simplicity and readability over enforced restrictions. The language trusts developers to follow conventions, and that trust has worked well across decades of real-world Python development. When you see a name in all caps, you and every other Python developer on your team know what it means without the language needing to lock the value at runtime.

This design also keeps Python flexible during development. You might temporarily reassign a constant to test different configurations without restarting the entire program. A language-level constant would block that workflow unless you modified source code or jumped through extra steps. Python gives you the readability of constants along with the freedom to override them when you genuinely need to, as long as you understand that doing so in production code breaks the convention and should never ship.

If your project uses a static type checker like mypy or pyright, you can add typing.Final to get the closest thing to enforced constants that Python offers. The annotation MAX_LOGIN_ATTEMPTS: Final = 5 tells the type checker to flag any reassignment as an error before your code runs, though Python itself ignores the annotation at runtime.

Here is a quick comparison of how Python's approach differs from other languages:

LanguageConstant mechanismEnforced at runtime?
PythonUPPER_CASE conventionNo (social contract)
Python + mypyUPPER_CASE + Final annotationNo (type checker catches)
JavaScript (ES6+)const keywordYes
Javafinal keywordYes

Constants versus configuration

Not every value that feels fixed should be a module-level constant. Configuration values that change between environments, such as database URLs, API keys, or feature flags, should live in environment variables or configuration files rather than hard-coded in Python source files.

Module-level constants work best for values that are truly universal to your program's logic: mathematical constants, default limits, standard file encodings, HTTP status codes, and similar values that do not depend on where the program runs. Keep environment-specific configuration separate from true constants so your code deploys cleanly across different environments without editing source files.

pythonpython
import os
 
# Configuration from environment (may differ per deployment)
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://localhost/mydb")
 
# True constants (same for every run)
BYTES_PER_KILOBYTE = 1024
HTTP_OK = 200

This separation keeps your code maintainable. When a limit changes from 100 to 200, you update one line instead of hunting through the file. When a new team member reads your code, each named constant explains itself. The uppercase convention is a small habit that pays off steadily as your projects grow. Revisit the article on Python variables any time you want to review how naming and assignment work before constants were introduced to your toolkit.

Rune AI

Rune AI

Key Insights

  • Python has no const keyword; use UPPER_CASE names to signal a value should not change.
  • Define constants at module level after imports or as UPPER_CASE class attributes.
  • typing.Final lets type checkers warn about reassignment, though Python itself does not block it.
  • Constants reduce magic numbers and make code self-documenting.
  • Reassigning a constant violates the convention and confuses readers, even though Python allows it.
RunePowered by Rune AI

Frequently Asked Questions

Does Python have a const keyword like other languages?

No. Python does not have a const keyword. Developers follow a naming convention: names written in all uppercase signal to other programmers that the value should stay unchanged. Python trusts developers to respect conventions rather than enforcing read-only behavior at the language level.

Can I enforce a constant in Python so it cannot be changed?

There is no built-in enforcement, but you can use typing.Final to declare that a name should not be reassigned, and type checkers like mypy or pyright will warn you. This does not stop Python at runtime, but it catches mistakes during development before the code ships.

Where should I define constants in my Python file?

Define constants at the top of a module, right after the import statements. Grouping related constants together makes them easy to find and update. If a constant is only used inside a class, define it as a class attribute in UPPER_CASE at the top of the class body.

Conclusion

Python does not enforce constants at the language level, but the UPPER_CASE convention gives you a clear, readable way to signal which values should remain unchanged. Treat those names as read-only, place them at the top of your module, and your code will be easier to reason about and safer to modify.