You have probably seen variable names written in all capital letters in Python code. That uppercase style is not random. It is the community's way of marking a value as a constant — something that should stay the same for the life of the program. This tutorial explains what that means in practice, when to reach for a constant, and how to write one correctly from your very first Python project.
Python does not have a built-in const keyword the way some other languages do. Any name you assign a value to can technically be reassigned later. Constants in Python are an agreement between developers: write the name in uppercase letters, and everyone understands it should not change. That agreement, documented in PEP 8, is what makes Python code readable and safe to maintain.
What Is a Constant?
A constant is a name that holds a value you do not intend to change. In Python, you signal that intent by writing the name entirely in uppercase letters, with underscores separating words. This pattern is called the ALL_CAPS convention, and it comes directly from PEP 8, Python's official style guide.
Here is a straightforward example. Imagine your program needs to know the maximum number of login attempts before locking an account:
Python does not prevent you from reassigning MAX_LOGIN_ATTEMPTS after you define it. The uppercase name is a convention, not a lock. Tools like pylint can warn you if your code reassigns a constant name, but the interpreter itself will not stop you.
If you need a value that is truly immutable at runtime, store it in a tuple or use typing.Final from the typing module. Final tells static type checkers like mypy to flag any reassignment as an error. For most beginners, the ALL_CAPS convention is all you need.
# Define a constant at the top of the module
MAX_LOGIN_ATTEMPTS = 5
def check_login(attempts):
if attempts >= MAX_LOGIN_ATTEMPTS:
return "Account locked."
return "Try again."
The name MAX_LOGIN_ATTEMPTS tells any reader immediately what the number means. If the security policy changes and the limit becomes 10, you update exactly one line instead of hunting through the entire file.
"Constants should be written in all capital letters with underscores separating words." — PEP 8, Python Software Foundation
Build a valid Python constant definition for the maximum file size in bytes. Click each token in the correct order:
MAX_FILE_SIZE, not max_file_size). The correct statement is MAX_FILE_SIZE = 10 * 1024 * 1024 — that multiplies 10 by 1,024 twice to express 10 megabytes in bytes. The distractor - is not part of this expression, and lowercase max_file_size would signal a regular variable, not a constant.
When Should You Use a Constant?
The most common signal that a value belongs in a constant is when that value appears more than once, has a meaning that raw text or a number does not communicate, or could change in the future and would be painful to update in multiple places. Three practical triggers help beginners decide:
The value never changes during a program run. Things like the speed of light, a tax rate, a maximum upload size, or a default timeout belong in constants. They are facts about the problem domain, not state that your program manipulates.
The raw value has no obvious meaning. If you encounter if retries > 5 in a code review, you immediately wonder: why five? What happens at six? Replacing it with if retries > MAX_RETRIES answers the question before it is asked.
The value appears in more than one place. Duplicating a literal integer or string in three functions means changing it requires touching three places and risking that you miss one. A constant gives you a single source of truth.
- Use as constant?
- Yes — it is a fixed rate set by policy, not something your code calculates at runtime.
- Example
TAX_RATE = 0.085— named, descriptive, easy to update in one place when the rate changes.
- Use as constant?
- No — this value changes as the user plays, so it belongs in a regular variable, not a constant.
- Example
score = 0thenscore += 10— mutating state is exactly what variables are for.
- Use as constant?
- Yes — the base URL is a configuration value that does not change at runtime. It is also likely referenced in multiple functions.
- Example
API_BASE_URL = "https://api.example.com/v1"— any function that makes a request can reference this single definition.
The code below defines a constant and uses it to calculate a price. One line violates the constant convention. Click the line you think is wrong, then hit check.
order_tax_rate = 0.10 and use that instead. Reassigning an ALL_CAPS name inside a function defeats the purpose of the convention and will confuse any reader who expects SALES_TAX_RATE to be stable.
Where to Put Your Constants
PEP 8 recommends placing constants at the module level — that means at the top of your Python file, after the import statements and before any function or class definitions. This placement makes them easy to find, easy to update, and straightforward to import into other modules.
A typical module looks like this:
For projects with many constants, a dedicated constants.py file is a common pattern. Any module in the project can then import exactly what it needs:
# constants.py
MAX_RETRIES = 5
TIMEOUT_SECONDS = 30
API_BASE_URL = "https://api.example.com/v1"
DEFAULT_PAGE_SIZE = 20
# api_client.py
from constants import API_BASE_URL, TIMEOUT_SECONDS, MAX_RETRIES
def fetch_user(user_id):
url = f"{API_BASE_URL}/users/{user_id}"
for attempt in range(MAX_RETRIES):
response = requests.get(url, timeout=TIMEOUT_SECONDS)
if response.ok:
return response.json()
return None
How to Use Constants in Python
Follow these four steps any time you spot a value in your code that belongs in a constant. This process takes under a minute and makes your code noticeably easier to read and maintain.
-
Identify the fixed value
Look for a numeric or string literal that never changes during program execution — a timeout duration, a rate, a file path, a status code, or any other configuration value. If you find yourself writing the same literal in more than one place, that is a strong signal.
-
Name it in ALL_CAPS
Assign the value to an uppercase name at module level. Use underscores to separate words:
MAX_RETRIES,DEFAULT_TIMEOUT,BASE_URL. Keep the name as descriptive as you can without being verbose. -
Place it at the top of the module
Move the definition after your
importstatements and before any function or class definitions. This makes it immediately visible to anyone reading the file and easy to change without scrolling through logic.
"Example quote goes here." — Source
Python Learning Summary Points
- Python does not enforce constants at the language level. The ALL_CAPS naming convention communicates intent to other developers and to static analysis tools like
mypyandpylint. - Use a constant when a value is fixed for the life of the program, when a raw literal has no obvious meaning on its own, or when the same literal appears in more than one location.
- Define constants at module level, after imports and before function or class definitions. For larger projects, collect all constants in a dedicated
constants.pyorconfig.pyfile and import from there. - Avoid reassigning a constant name inside a function or method. If you need a locally different value, assign it to a regular lowercase variable instead.
- If you need runtime enforcement, use
typing.Finalto tell static type checkers that a name must not be reassigned after its initial definition.
The habit of reaching for a named constant instead of an inline literal is one of the smallest changes you can make with the largest payoff in readability. The next time you write a number or string that "just works," ask yourself: does this value have a name? If the answer is yes, give it one.
Frequently Asked Questions
A constant in Python is a variable whose value is intended to remain unchanged throughout a program. Python does not enforce constants at the language level, so the ALL_CAPS naming convention signals to other developers that a value should not be reassigned.
You declare a constant in Python by assigning a value to a name written in ALL_CAPS with underscores separating words, such as MAX_RETRIES = 5. By convention, this name is placed at the top of a module, outside any function or class.
No, Python does not enforce constants. You can technically reassign an ALL_CAPS name, and the interpreter will not raise an error. The convention is enforced by developer discipline, code reviews, and static analysis tools such as pylint.
A magic number is a numeric or string literal that appears directly in code without explanation, such as if retries > 5. Replacing it with a named constant like MAX_RETRIES = 5 makes the code self-documenting and ensures that changing the value requires editing only one place.
Constants should be defined at the module level, after imports and before any function or class definitions. This placement makes them easy to find, change, and import from other modules.
Yes. A common pattern is to place all constants in a dedicated file such as config.py or constants.py and import them with a statement like from constants import MAX_RETRIES. This keeps configuration values in a single, maintainable location.
Both are created with a simple assignment statement. The difference is intent and naming: a variable is expected to change during program execution, while a constant is expected to stay fixed. Python communicates that intent through the ALL_CAPS naming convention.
Yes. Values that are fixed for the duration of a program run — such as API base URLs, port numbers, timeout durations, and file paths — are good candidates for constants. They benefit from a single definition point and a descriptive name.