Tip 12 Avoid “Magic” Values

Pythonic Programming — by Dmitry Zinoviev (20 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Distinguish Parameters and Arguments | TOC | Enumerate Your Constants 👉

★2.7, 3.4+ A “magic” value is a constant (usually numerical) that is not self-explanatory, as if included in the program by magical forces rather than by powers of reason. Here is an example of a “magic” value:

​ distance = 1.6 * distance

If you are familiar with the imperial length units, you may recognize the conversion from miles to kilometers. Others would have to guess. Things get incredibly cumbersome when two or more constants in the program have the same value but different purposes, as in the Tic-Tac-Toe field construction statement (Tip 26, Transpose with zip()):

​ field = [[​' '​] * 3 ​for​ _ ​in​ range(3)]

The first number 3 is the number of columns; the second number 3 is the number of rows. If the field is square (as in the “classic” Tic-Tac-Toe), the numbers are equal, but generally, they do not have to be. Your prospective reader (and that could be you two weeks later) would wonder: If I change the first 3, should I also change the other 3? And how about some other 3’s in the rest of the program?

The simplest way to avoid “magic” values is to define Python “constants” (they are not true constants, see Tip 5, Keep Letter Case Consistent) and use them consistently throughout the program:

​ MILES_TO_KM = 1.6…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.