Skip to content

magic number

A magic number is an unnamed numeric literal that sits directly in your source code without any explanation of what it stands for. The value works fine at runtime, but whoever reads the code next has to guess why that particular number is there.

Magic numbers get expensive once they spread. The same value tends to appear in several places, so changing it means tracking down every occurrence and hoping you don’t touch an unrelated number that happens to look identical. A single number can also mean two different things in the same file, which makes a search-and-replace edit risky.

The remedy is to give the value a name. Swapping magic numbers for named constants states your intent and leaves you one place to edit. When the number belongs to a fixed set of related options, such as status codes or modes, an Enum groups those options under a single named type instead of scattered loose constants.

The term has a second, unrelated sense in file formats and protocols, where a magic number is a fixed byte signature at the start of a file. Python exposes one as importlib.util.MAGIC_NUMBER, which holds the bytes that identify the bytecode version of a .pyc file.

Example

Say you’re reviewing a function that totals an online order and you run into two bare numbers:

Language: Python
>>> def order_total(subtotal):
...     return subtotal * (1 + 0.0825) + 4.99
...
>>> order_total(100)
113.24

Naming the values turns the same arithmetic into something you can read:

Language: Python
>>> SALES_TAX_RATE = 0.0825
>>> SHIPPING_FEE = 4.99

>>> def order_total(subtotal):
...     return subtotal * (1 + SALES_TAX_RATE) + SHIPPING_FEE
...
>>> order_total(100)
113.24

Both versions return the same total, but only the second one tells you that 0.0825 is a tax rate and 4.99 is a flat shipping fee. When the tax rate changes, you edit one named constant instead of grepping for every 0.0825 in the codebase.

To see what that costs across a whole project, raise the tax rate below from 8.25 percent to 9.5 percent, first with bare literals and then with a named constant:

Interactive diagram — enable JavaScript to view.
Python Constants: Improve Your Code's Maintainability

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 Martin Breuss • Updated Aug. 29, 2026