liveBook · Manning

Magic number

As explained in Learn AI-Assisted Python Programming, Second Edition

A magic number is an unexplained numeric literal embedded directly in code instead of being represented by a named parameter or variable.

A magic number is a raw numeric literal whose purpose is unclear because it appears directly in code instead of using a named parameter or variable. section 10.3.3

When a number controls gameplay or another changeable behavior, give it a meaningful parameter or variable name. Assign its concrete value as high-level as possible, such as when the game starts. section 10.3.3

Configurable guessing game

Instead of embedding four digits and 100 guesses inside a function, define the secret-code length and maximum guesses as parameters. Different calls can then change the gameplay without modifying the function. section 10.3.3

When you encounter a raw number, ask:

  • Could this number be a parameter or variable with a useful name? section 10.3.3
  • Can the value be supplied at the highest appropriate level rather than fixed inside the function? section 10.3.3

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Defines magic numbers and gives a review heuristic, but does not develop broader refactoring techniques.
Examples
Uses secret-code length and maximum guesses in a configurable guessing game.
What it assumes
Assumes basic familiarity with code, functions, parameters, and variables.
What you can do after
Apply it by replacing changeable raw numbers with named parameters or variables.
How it connects
Connects magic numbers with parameters, variables, functions, and general-purpose function design.

Also explained in

Compare how 2 books explain magic number →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.