4.9 Constants
Why Python has no language-enforced constants, the UPPER_SNAKE_CASE naming convention, and best practices for defining values that shouldn't change.
Concept of Constants
What Is It?
A value that’s meant to never change after it’s set.
Why Doesn’t Python Enforce It?
Python has no true language-enforced constant — unlike const in other languages, nothing stops you from reassigning an UPPER_CASE name. “Constants” in Python are a naming convention, not a compiler guarantee.
Naming Convention
How Is It Used?
Constants are written in UPPER_SNAKE_CASE to visually signal “don’t reassign this” to anyone reading the code:
MAX_RETRIES = 3
DEFAULT_TIMEOUT = 30
API_BASE_URL = "https://api.example.com"
Best Practices
- Define constants at the top of the module, right after imports
- Use
UPPER_SNAKE_CASEconsistently so violations of the convention stand out - For values that truly must be immutable, use a tuple or
Enumrather than relying on naming alone
Quick Interview Answer
“Python has no
constkeyword — a ‘constant’ is purely a naming convention:UPPER_SNAKE_CASE, defined at the top of a module, meant to signal ‘don’t reassign this.’ Nothing at the language level actually prevents reassignment. If true immutability matters, use a tuple or anEnuminstead of relying on the naming convention alone.”
Common Mistakes
- Believing
UPPER_CASE = valueis protected from reassignment the wayconstis in JavaScript or Java — it is not; it’s purely convention. - Defining constants scattered throughout a module instead of grouped at the top, making them harder for a reader to find.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form