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_CASE for 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, or 42 with descriptive constants such as DISCOUNT_RATE, PI, or ULTIMATE_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:

Python 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:

Python 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.

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.

intermediate python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 14, 2026 • Reviewed by Martin Breuss