Python
Programming
Coding
Constants in Python
Software Development

How do I create a constant in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Python does not have a dedicated const keyword, so creating a constant is mostly about communicating intent and choosing the right data structure. In practice, most Python code uses module-level names, type hints, and immutable containers to make values behave like constants.

Use Module-Level Names for Simple Constants

The standard Python convention is to define constants at module scope with uppercase names. This does not prevent reassignment at runtime, but it clearly signals that the value should not change.

python
1# settings.py
2from typing import Final
3
4SECONDS_PER_DAY: Final = 86_400
5DEFAULT_PORT: Final = 8080
6API_ROOT: Final = "https://api.example.com"
7
8
9def build_status_url(job_id: str) -> str:
10    return f"{API_ROOT}/jobs/{job_id}"

The Final annotation helps linters and type checkers such as mypy catch accidental reassignment:

python
1from settings import DEFAULT_PORT
2
3print(DEFAULT_PORT)
4
5# A type checker should flag this.
6# DEFAULT_PORT = 9000

This is the idiomatic answer for most projects. If the value is shared across files and should stay stable, put it in one module and import it where needed.

Use Immutable Types When the Value Has Structure

Uppercase names are only a convention. If the object itself is mutable, code can still change it. For grouped configuration, use immutable types so the constant is harder to corrupt by accident.

python
1from dataclasses import dataclass
2
3
4@dataclass(frozen=True)
5class AppConfig:
6    host: str
7    port: int
8    debug: bool
9
10
11DEFAULT_CONFIG = AppConfig(
12    host="127.0.0.1",
13    port=8080,
14    debug=False,
15)
16
17print(DEFAULT_CONFIG.host)

For named choices, an Enum is even better because it restricts the allowed values:

python
1from enum import Enum
2
3
4class LogLevel(Enum):
5    DEBUG = "debug"
6    INFO = "info"
7    ERROR = "error"
8
9
10DEFAULT_LEVEL = LogLevel.INFO
11print(DEFAULT_LEVEL.value)

These patterns make your intent more obvious than using plain strings everywhere.

Pick the Right Level of Strictness

Most code does not need hard enforcement. The combination of uppercase names, Final, and immutable objects is usually enough. If you need stronger guarantees, the better question is often whether the value belongs in code at all.

For example:

  • Build-time constants such as file extensions or unit conversions fit well in a Python module.
  • Deployment-specific values such as API keys or database URLs usually belong in environment variables.
  • User-editable settings often belong in JSON, TOML, or YAML config files.

A small example using environment variables looks like this:

python
1import os
2
3
4TIMEOUT_SECONDS = int(os.getenv("TIMEOUT_SECONDS", "30"))
5
6print(TIMEOUT_SECONDS)

That value behaves like a constant during a program run, but it is configured outside the source code, which is often the better design.

Common Pitfalls

The biggest misconception is thinking uppercase names create true constants. They do not. This works:

python
MAX_RETRIES = 3
MAX_RETRIES = 5

Python allows it. The uppercase spelling is a social contract, not a language rule.

Another common mistake is calling a mutable object a constant:

python
ALLOWED_HOSTS = []
ALLOWED_HOSTS.append("localhost")

The name stayed the same, but the object changed. If you need immutability, prefer tuples, frozen dataclasses, or enums.

It is also easy to scatter the same value across many modules. That creates drift when one copy changes and others do not. Put shared constants in a single module and import them instead of duplicating them.

Finally, avoid storing secrets as code constants in a repository. API tokens, passwords, and private keys should come from a secret manager or environment variables.

Summary

  • Python has no built-in const keyword, so constants are created by convention and design.
  • Module-level uppercase names are the standard way to define simple constants.
  • 'typing.Final helps static analysis tools catch accidental reassignment.'
  • Frozen dataclasses, tuples, and enums are better choices when the constant has internal structure.
  • External configuration values often belong in environment variables or config files instead of source code.

Course illustration
Course illustration

All Rights Reserved.