Avoid magic literals

Best practices for organizing functionality.

What is a “magic literal”?

A magic literal is a raw value (number, string, None, etc.) that appears in code without a name explaining its meaning or origin. They harm readability, hide intent, and make changes risky—because the same value might be duplicated in many places.

Rule of thumb: If a value has domain meaning (tax rate, role name, error code, feature flag, file path, regex, etc.), name it once and reuse that name everywhere.

Benefits

  • Clear intent (self-documenting)
  • Single source of truth (change in one place)
  • Fewer bugs during refactors
  • Easier testing & configuration

Example 1 - numeric literal

Problematic code

Where does the value 0.085 come from? Why is it there? Not knowing this harms maintainability.

def final_price(subtotal):
    # Why 0.085? City tax? Promo? Future me has no idea.
    return subtotal * (1 + 0.085)

Fixed with a constant that conveys intent

Constants are variables that don’t vary. They are set once and not changed. In Python, the convention is to name Python constants as ALL_UPPERCASE_AND_UNDERSCORES.

CITY_SALES_TAX_RATE = 0.085  # 8.5% city sales tax

def final_price(subtotal: float) -> float:
    return subtotal * (1 + CITY_SALES_TAX_RATE)

Why this is better: The constant gives the number meaning, centralizes the value, and invites documentation and tests around that concept. Keep constants close to where they’re used (module-level), or in a dedicated constants.py if shared broadly.

When a literal is not magic

  • Sentinel/obvious values: 0, 1, -1, True, False, "" used in generic math or indexing (e.g., arr[-1]) are usually fine.
  • Short-lived throwaway code/tests: Inline values in extremely small, clear scopes can be acceptable.
  • Data structure examples: Literals inside illustrative examples or test fixtures are usually okay unless they are likely to change.
Last modified October 29, 2025.