Skip to content
Arithmetic construction through Python's data model

Build numbers, one rule at a time.

Start with zero and successor. Follow each mathematical definition into a class, method, branch, trace, and test.

The construction
  1. Zero and successorconstruct natural numbers and addition
  2. Pairs of naturalsidentify pairs with the same difference
  3. Pairs of integersidentify pairs with the same ratio
  4. Expressions and intervalsidentify a real root that is not rational

What this course assumes

You should be comfortable with ordinary Python syntax: functions, classes, conditionals, loops, collections, exceptions, and type annotations. You do not need prior knowledge of Peano arithmetic, constructed number systems, polynomials, or this repository.

The course teaches the Python mechanisms that matter to this implementation:

  • operator dispatch such as a + b calling a.__add__(b);
  • decorators that change a public call without changing its mathematical core;
  • generated and suppressed dataclass methods;
  • __post_init__, properties, total_ordering, and frozen values;
  • coercion, NotImplemented, equality, and hashing across a numeric tower.

Nothing is installed on your computer. Experiments run in the browser.

How understanding accumulates

1 · Definitionstate the object and its rules 2 · Representationsee which fields store it 3 · Implementationmap each rule to a method and branch 4 · Tracepredict the execution before running it 5 · Testread what concrete behavior is checked 6 · Boundaryseparate proof, design choice, and optimization

A trace is not a self-explanatory derivation. First read the relevant implementation; then use the trace to check which rule and branch actually ran. Every chapter includes the source excerpt needed for its questions and links to the complete source and tests.

Learning route

The finish line is not merely obtaining the right answer. You should be able to say which definition was executed, how the value was represented, which branch produced a trace line, and what the test does—and does not—establish.

Begin with Python's data model and metaprogramming →