Skip to content

Options and doctests

A command-line script written without annotations: argparse options, doctests on the functions, a functools.lru_cache recursion, and a small vector class used through +, *, and <. The folder's pyproject.toml turns strict mode off. ppy run types the functions from the parser's type=int options, from the operators applied to the class, and from the calls and doctests, and compiles them.

Run it

python  puzzles.ppy
ppy run puzzles.ppy
ppy run puzzles.ppy --limit 1000 --terms 50 --steps 1000 --seed 3
ppy explain puzzles.walk
ppy explain --summary puzzles.ppy

What it prints

python puzzles.ppy

# sieve: 0.327 s
primes below 5000000 : 348513 the last 4999999
# mean_gap: 0.012 s
mean gap: 14.3467
# partitions: 0.045 s
partitions of 400 : 6727090051741041926
# walk: 0.966 s
farthest squared distance, times it moved: (7065320, 2681)

ppy run puzzles.ppy

# sieve: 0.189 s
primes below 5000000 : 348513 the last 4999999
# mean_gap: 0.001 s
mean gap: 14.3467
# partitions: 0.035 s
partitions of 400 : 6727090051741041926
# walk: 0.316 s
farthest squared distance, times it moved: (7065320, 2681)

ppy run puzzles.ppy --limit 1000 --terms 50 --steps 1000 --seed 3

# sieve: 0.000 s
primes below 1000 : 168 the last 997
# mean_gap: 0.000 s
mean gap: 5.9581
# partitions: 0.000 s
partitions of 50 : 204226
# walk: 0.000 s
farthest squared distance, times it moved: (5972, 75)

ppy explain puzzles.walk

23 lines
function: walk
qualname: puzzles.walk
semantic type: (int, int) -> tuple[int, int]
effects: Alloc, MayRaise[TypeError, ValueError, ZeroDivisionError], ReadObject, WriteObject
purity: impure
optimization: O2
python backend: optimized
llvm backend: native
python boundary: a generated CPython-ABI wrapper
jit: not requested
parallel: rejected
reason: `farthest` carries a dependency across iterations
reductions: +
representation:
  steps: int -> i64 (guarded)
  seed: int -> i64 (guarded)
  return: tuple[int, int] -> PyObject*
inferred (not annotated):
  steps: int, from 1 call (puzzles.ppy:107)
  seed: int, from 1 call (puzzles.ppy:107)
  (the Python boundary checks these at each call, and runs the Python body otherwise)
  return: tuple[int, int], from the body's return statements
refinements: len == 2

ppy explain --summary puzzles.ppy

10 functions, 61 statements
  native, called from Python              3 functions ( 30%)       27 statements ( 44%)
  native, called from native code         6 functions ( 60%)       12 statements ( 20%)
  Python                                  1 functions ( 10%)       22 statements ( 36%)

what keeps functions in Python, by statements kept out (a function can count under more than one):
       22 statements      1 functions  calls a Python function whose `argparse.ArgumentParser` result native code cannot take back
      call a function that changes nothing (its result is checked, and falls back), or keep the call out of the hot function
      see https://ppy.franknoh.dev/latest/guide/native-effects/
      puzzles.ppy:87 puzzles.main

native, but Python calls the Python body (why its boundary is not used):
      1 functions  calls itself without a loop; CPython's recursion limit stays in force
      3 functions  the boundary crossing costs more than the body saves
      2 functions  the objects it makes cost more to hand to Python than its loops save

The program

  • Vector(x, y) has __add__, __mul__ by a number, __lt__ that compares squared lengths, and norm(), the squared length.
  • sieve(limit) marks composites in a list of bools and returns the primes up to limit.
  • partitions(total, largest) counts the ways to write total as a sum of parts no larger than largest, under @functools.lru_cache.
  • walk(steps, seed) takes steps steps of a random walk on the grid (from a linear congruential generator), each one a Vector added to the position. It keeps the farthest point, comparing points with <, and returns its squared distance and how many times it moved.
  • mean_gap(primes, tolerance=EPSILON) is the mean gap between consecutive primes.
  • main() reads --limit, --terms, --steps, and --seed with argparse and prints each result. The lines that start with # are timings, which differ between runs.

Where the types come from

No parameter is annotated. In strict mode ppy check puzzles.ppy reports 27 errors: twelve E1201, one per parameter, and the reads and calls that follow from them. With strict = false:

  • Options. parser.add_argument("--limit", type=int, default=5_000_000) makes args.limit an int: the parser gives it a value of that type whether or not the option is on the command line. sieve(args.limit) is then a call with an int, and so are the calls of partitions and walk. An option with no default that is not required could be None and would not count.
  • Operators. position + step * (1 + state % 2) in walk is a call of Vector.__mul__ with an int and of Vector.__add__ with a Vector, and farthest < position is a call of Vector.__lt__. A comparison method is only typed as taking its own class, since sorting and lookups call it with two of the class's objects. Written as farthest = max(farthest, position), the comparison counts the same way, and walk stays native: max of two objects compares them as CPython does, position > farthest through the reflected farthest < position, and keeps the first of equals.
  • Decorators. lru_cache keeps the function's parameters, so partitions is typed from its calls as an undecorated function would be. A project decorator counts the same way only when its wrapper is made with functools.wraps(fn) and does nothing but call fn(*args, **kwargs).
  • Defaults. tolerance=EPSILON is a module constant written as a literal, so it counts as a call passing a float.
  • Doctests. Here every function is also called from main, so the doctests only agree with the calls. Without main, they would type some of the same parameters: sieve(20) gives limit an int, and a * 3 on the doctest's a = Vector(1, 2) gives __mul__'s factor one, and the Vector(3, 4) and Vector(2, 2) operands of + and < give other the class: a constructor call of a project class counts as an operand, and so does a name an earlier example bound to one (other: puzzles.Vector, from 1 doctest call).

main itself stays in Python: the parser is a Python object native code has no value for. Everything it calls is native, and ppy explain --summary counts partitions as native but called through its Python body by Python, because it calls itself without a loop and CPython's recursion limit stays in force.

The boundary still checks

walk is native and checks its two arguments when Python calls it. The third command passes small options: the values are still ints, so nothing changes but the sizes. From --terms 406 the count of partitions passes 64 bits. Python calls partitions through its Python body already, so the sum is CPython's own and every path prints the same number.

Timing

Wall time for the whole program, the mean of five runs, measured from a checkout under /tmp on one machine (Python 3.14, an Intel Core Ultra 9 386H under WSL2):

seconds
python puzzles.ppy 1.34
ppy run puzzles.ppy, after the first run built the cache 0.53

Each part, as the program prints it, the mean of five runs in seconds:

part CPython ppy run
sieve(5_000_000) 0.304 0.143
mean_gap 0.012 0.001
partitions(400, 400) 0.045 0.039
walk(2_000_000, 7) 0.934 0.281

There is no standalone build: main stays in Python.

Where the code comes from

puzzles.ppy is hand-written.

Read on: Types from call sites and Classes.

56_options_and_doctests/puzzles.ppy

import argparse
import functools
import time

EPSILON = 1e-9


class Vector:
    """
    >>> a = Vector(1, 2)
    >>> (a + Vector(3, 4)).norm(), (a * 3).norm(), a < Vector(2, 2)
    (52, 45, True)
    """

    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __mul__(self, factor):
        return Vector(self.x * factor, self.y * factor)

    def __lt__(self, other):
        return self.norm() < other.norm()

    def norm(self):
        return self.x * self.x + self.y * self.y


def sieve(limit):
    """
    >>> sieve(20)
    [2, 3, 5, 7, 11, 13, 17, 19]
    """
    marks = [True] * (limit + 1)
    marks[0] = marks[1] = False
    for n in range(2, int(limit**0.5) + 1):
        if marks[n]:
            for multiple in range(n * n, limit + 1, n):
                marks[multiple] = False
    return [n for n in range(limit + 1) if marks[n]]


@functools.lru_cache(maxsize=None)
def partitions(total, largest):
    """
    >>> for n in [1, 5, 10]:
    ...     print(partitions(n, n))
    1
    7
    42
    """
    if total == 0:
        return 1
    if total < 0 or largest == 0:
        return 0
    return partitions(total - largest, largest) + partitions(total, largest - 1)


def walk(steps, seed):
    position = Vector(0, 0)
    farthest = Vector(0, 0)
    records = 0
    state = seed
    for _ in range(steps):
        state = (state * 1103515245 + 12345) % 2147483648
        step = Vector(state % 3 - 1, state // 3 % 3 - 1)
        position = position + step * (1 + state % 2)
        if farthest < position:
            farthest = position
            records += 1
    return farthest.norm(), records


def mean_gap(primes, tolerance=EPSILON):
    if len(primes) < 2:
        return 0.0
    total = 0.0
    for i in range(1, len(primes)):
        total += primes[i] - primes[i - 1]
    result = total / (len(primes) - 1)
    return 0.0 if result < tolerance else result


def main():
    parser = argparse.ArgumentParser(description="number puzzles")
    parser.add_argument("--limit", type=int, default=5_000_000)
    parser.add_argument("--terms", type=int, default=400)
    parser.add_argument("--steps", type=int, default=2_000_000)
    parser.add_argument("--seed", type=int, default=7)
    args = parser.parse_args()
    start = time.perf_counter()
    primes = sieve(args.limit)
    print(f"# sieve: {time.perf_counter() - start:.3f} s")
    print("primes below", args.limit, ":", len(primes), "the last", primes[-1])
    start = time.perf_counter()
    gap = mean_gap(primes)
    print(f"# mean_gap: {time.perf_counter() - start:.3f} s")
    print("mean gap:", round(gap, 4))
    start = time.perf_counter()
    count = partitions(args.terms, args.terms)
    print(f"# partitions: {time.perf_counter() - start:.3f} s")
    print("partitions of", args.terms, ":", count)
    start = time.perf_counter()
    farthest = walk(args.steps, args.seed)
    print(f"# walk: {time.perf_counter() - start:.3f} s")
    print("farthest squared distance, times it moved:", farthest)


if __name__ == "__main__":
    main()

Source: examples/56_options_and_doctests.