constants
Constants complement variables by giving fixed values (such as configuration options, limits, or domain-specific numbers) a stable, descriptive name.
When working with constants, the following best practices can improve clarity and maintainability:
- Use
UPPER_SNAKE_CASEfor module-level constants: Python doesn’t enforce constants at runtime, so following the PEP 8 naming convention signals intent. - Replace magic numbers with named constants: Replace unexplained literal values like
0.9,3.14, or42with descriptive constants such asDISCOUNT_RATE,PI, orULTIMATE_ANSWER. This removes magic numbers and gives you a single source of truth when a value is reused. - Prefer immutable values for shared data: Use immutable types such as numbers, strings, tuples, or frozen data structures to reduce accidental modification.
To see some of these ideas in action, consider the following code example:
🔴 Avoid this:
salary.py
def compute_net_salary(hours):
return hours * 35 * (1 - (0.04 + 0.10))
This function hides meaning behind numeric literals, forcing readers to infer intent from the numbers alone.
✅ Favor this:
salary.py
HOURLY_SALARY = 35
SOCIAL_SECURITY_TAX_RATE = 0.04
FEDERAL_TAX_RATE = 0.10
def compute_net_salary(hours):
return (
hours
* HOURLY_SALARY
* (1 - (SOCIAL_SECURITY_TAX_RATE + FEDERAL_TAX_RATE))
)
In this version, HOURLY_SALARY, SOCIAL_SECURITY_TAX_RATE, and FEDERAL_TAX_RATE are defined as module-level constants, making the intent explicit and keeping the values in one place.
Related Resources
Tutorial
Python Constants: Improve Your Code's Maintainability
In this tutorial, you'll learn how to properly define constants in Python. By coding a bunch of practical example, you'll also learn how Python constants can improve your code's readability, reusability, and maintainability.
For additional information on related topics, take a look at the following resources:
- Build Enumerations of Constants With Python's Enum (Tutorial)
- Python's Mutable vs Immutable Types: What's the Difference? (Tutorial)
- Defining Python Constants for Code Maintainability (Course)
- Building Enumerations With Python's enum (Course)
- Differences Between Python's Mutable and Immutable Types (Course)