Skip to main content

Python as a metaprogramming language

Everything so far has treated @jit as a switch: put it on a function and the function gets faster. That framing hides the most useful thing about a JIT embedded in a host language.

Numba does not compile Python. It compiles a small language that happens to be spelled with Python syntax — a few scalar types, arrays, tuples, a handful of NumPy functions, range. Most of Python is simply not available inside a nopython function: no dictionaries of arbitrary objects, no classes, no fractions, no scipy, no I/O.

The usual reaction is to treat that as a limitation to work around. The more productive reading is that there are two languages and two times:

language runs at has access to
stage 1 all of Python generation time the entire ecosystem
stage 2 numba’s subset run time machine registers

Stage 1’s job is to write stage 2. That is metaprogramming, and Python is unusually good at it: closures capture values, decorators rewrite definitions, descriptors rewrite attribute access. This notebook builds that idea up from a single function to a class API, and then takes the class API apart again to see exactly what the syntax is hiding — because the pattern’s cost is paid entirely in Python’s object model, not in the generated code.

import time

import numpy as np
from numba import jit


def timeit(fn, *args, n=200):
    """Median-ish seconds per call, after a warm-up call to force compilation."""
    fn(*args)
    t0 = time.perf_counter()
    for _ in range(n):
        fn(*args)
    return (time.perf_counter() - t0) / n

The motivating gap: constants the compiler cannot see

Evaluate a polynomial at every point of an array, by Horner’s rule. Written the ordinary way, the coefficients arrive as an argument:

@jit("f8[::1](f8[::1], f8[::1])", nopython=True, nogil=True)
def horner_runtime(x, coeffs):
    out = np.empty_like(x)
    for i in range(x.size):
        acc = 0.0
        for j in range(coeffs.size):
            acc = acc * x[i] + coeffs[j]
        out[i] = acc
    return out


COEFFS = [1.0, -3.0, 2.5, 0.5, -1.25, 7.0, 0.125, -2.0]
coeffs_array = np.array(COEFFS)
x = np.random.randn(1_000_000)

This is already good code — typed, unboxed, no Python objects in the loop. But look at what the compiler is not allowed to assume. coeffs.size is a runtime value, so the inner loop needs a trip-count test on every iteration. coeffs[j] is a runtime load, so each multiply waits on memory. And because the trip count is unknown, the outer loop cannot be vectorised across i: LLVM would have to prove the inner loop’s behaviour is uniform, and it cannot.

Every one of those obstacles is the same obstacle — the coefficients are data, and the compiler only optimises code. In this program, though, they are not really data. They are fixed the moment you decide which polynomial you want.

runtime_coeffs = timeit(horner_runtime, x, coeffs_array)
print(f"coefficients as an argument: {runtime_coeffs * 1e3:.2f} ms")
coefficients as an argument: 1.25 ms

Stage 1: an ordinary Python function that writes a numba function

Move the coefficients from the argument list into a closure, and move the decision about which polynomial we are compiling from run time to generation time:

def make_horner(coeffs):
    """Compile a Horner evaluator specialised to `coeffs`."""
    coeffs = tuple(coeffs)  # a tuple is a compile-time type; a list is a runtime container

    @jit("f8[::1](f8[::1])", nopython=True, nogil=True)
    def horner(x):
        out = np.empty_like(x)
        for i in range(x.size):
            acc = 0.0
            for c in coeffs:
                acc = acc * x[i] + c
            out[i] = acc
        return out

    return horner


horner_baked = make_horner(COEFFS)

Nothing here is a numba feature. make_horner is a plain higher-order function; the only thing that changed is when coeffs is known. Same answers:

np.testing.assert_allclose(horner_baked(x), horner_runtime(x, coeffs_array))

baked_coeffs = timeit(horner_baked, x)
print(f"coefficients in a closure  : {baked_coeffs * 1e3:.2f} ms")
print(f"speed-up                   : {runtime_coeffs / baked_coeffs:.1f}x")
coefficients in a closure  : 0.16 ms
speed-up                   : 7.6x

Several times faster, from moving one name across a scope boundary. It is worth being precise about why, because “the compiler sees a constant” is three separate wins stacked on top of each other.

Peeling it: what the closure actually became

In CPython a closure variable is a cell — a box that is read at run time, once per access:

import dis

print("free variables:", horner_baked.py_func.__code__.co_freevars)
print("cell contents:", horner_baked.py_func.__closure__[0].cell_contents)
dis.dis(horner_baked.py_func)
free variables: ('coeffs',)
cell contents: (1.0, -3.0, 2.5, 0.5, -1.25, 7.0, 0.125, -2.0)
  --           COPY_FREE_VARS           1

   5           RESUME                   0

   7           LOAD_GLOBAL              0 (np)
               LOAD_ATTR                3 (empty_like + NULL|self)
               LOAD_FAST_BORROW         0 (x)
               CALL                     1
               STORE_FAST               1 (out)

   8           LOAD_GLOBAL              5 (range + NULL)
               LOAD_FAST_BORROW         0 (x)
               LOAD_ATTR                6 (size)
               CALL                     1
               GET_ITER
       L1:     FOR_ITER                40 (to L4)
               STORE_FAST               2 (i)

   9           LOAD_CONST               0 (0.0)
               STORE_FAST               3 (acc)

  10           LOAD_DEREF               5 (coeffs)
               GET_ITER
       L2:     FOR_ITER                25 (to L3)
               STORE_FAST               4 (c)

  11           LOAD_FAST_BORROW_LOAD_FAST_BORROW 48 (acc, x)
               LOAD_FAST_BORROW         2 (i)
               BINARY_OP               26 ([])
               BINARY_OP                5 (*)
               LOAD_FAST_BORROW         4 (c)
               BINARY_OP                0 (+)
               STORE_FAST               3 (acc)
               JUMP_BACKWARD           27 (to L2)

  10   L3:     END_FOR
               POP_ITER

  12           LOAD_FAST_BORROW_LOAD_FAST_BORROW 49 (acc, out)
               LOAD_FAST_BORROW         2 (i)
               STORE_SUBSCR
               JUMP_BACKWARD           42 (to L1)

   8   L4:     END_FOR
               POP_ITER

  13           LOAD_FAST_BORROW         1 (out)
               RETURN_VALUE

LOAD_DEREF is the giveaway: for CPython, coeffs is a lookup, no different in kind from loading an argument. The tuple is not special, and interpreting this bytecode would be no faster than the runtime-coefficient version.

Numba reads the same closure, but at compile time — it opens the cell while compiling and treats what it finds as a literal. That shows up in the typed IR under a name numba only uses for exactly this:

horner_baked.inspect_types()
horner (Array(float64, 1, 'C', False, aligned=True),)
--------------------------------------------------------------------------------
# File: /tmp/ipykernel_659235/4175210869.py
# --- LINE 5 --- 
# label 0
#   x = arg(0, name=x)  :: array(float64, 1d, C)

@jit("f8[::1](f8[::1])", nopython=True, nogil=True)

# --- LINE 6 --- 

def horner(x):

    # --- LINE 7 --- 
    #   $6load_global.0 = global(np: <module 'numpy' from '/home/kolen/.cache/Linux-x86_64/pixi/envs/jit_comparison-4669063116758098887/envs/default/lib/python3.14/site-packages/numpy/__init__.py'>)  :: Module(<module 'numpy' from '/home/kolen/.cache/Linux-x86_64/pixi/envs/jit_comparison-4669063116758098887/envs/default/lib/python3.14/site-packages/numpy/__init__.py'>)
    #   $16load_attr.1 = getattr(value=$6load_global.0, attr=empty_like)  :: Function(<built-in function empty_like>)
    #   del $6load_global.0
    #   out = call $16load_attr.1(x, func=$16load_attr.1, args=[Var(x, 4175210869.py:5)], kws=(), vararg=None, varkwarg=None, target=None)  :: (Array(float64, 1, 'C', False, aligned=True), omitted(default=None)) -> array(float64, 1d, C)
    #   del $16load_attr.1

    out = np.empty_like(x)

    # --- LINE 8 --- 
    #   $48load_global.5 = global(range: <class 'range'>)  :: Function(<class 'range'>)
    #   $60load_attr.8 = getattr(value=x, attr=size)  :: int64
    #   $80call.9 = call $48load_global.5($60load_attr.8, func=$48load_global.5, args=[Var($60load_attr.8, 4175210869.py:8)], kws=(), vararg=None, varkwarg=None, target=None)  :: (int64,) -> range_state_int64
    #   del $60load_attr.8
    #   del $48load_global.5
    #   $88get_iter.10 = getiter(value=$80call.9)  :: range_iter_int64
    #   del $80call.9
    #   $phi90.0 = $88get_iter.10  :: range_iter_int64
    #   del $88get_iter.10
    #   jump 90
    # label 90
    #   $90for_iter.1 = iternext(value=$phi90.0)  :: pair<int64, bool>
    #   $90for_iter.2 = pair_first(value=$90for_iter.1)  :: int64
    #   $90for_iter.3 = pair_second(value=$90for_iter.1)  :: bool
    #   del $90for_iter.1
    #   $phi94.1 = $90for_iter.2  :: int64
    #   del $90for_iter.2
    #   branch $90for_iter.3, 94, 174
    # label 94
    #   del $90for_iter.3
    #   i = $phi94.1  :: int64
    #   del $phi94.1
    # label 174

    for i in range(x.size):

        # --- LINE 9 --- 
        #   acc = const(float, 0.0)  :: float64
        #   acc.2 = acc  :: float64
        #   del acc

        acc = 0.0

        # --- LINE 10 --- 
        #   $100load_deref.3 = freevar(coeffs: (1.0, -3.0, 2.5, 0.5, -1.25, 7.0, 0.125, -2.0))  :: UniTuple(float64 x 8)
        #   $102get_iter.4 = getiter(value=$100load_deref.3)  :: iter(UniTuple(float64 x 8))
        #   del $100load_deref.3
        #   $phi104.1 = $102get_iter.4  :: iter(UniTuple(float64 x 8))
        #   del $102get_iter.4
        #   jump 104
        # label 104
        #   $104for_iter.2 = iternext(value=$phi104.1)  :: pair<float64, bool>
        #   $104for_iter.3 = pair_first(value=$104for_iter.2)  :: float64
        #   $104for_iter.4 = pair_second(value=$104for_iter.2)  :: bool
        #   del $104for_iter.2
        #   $phi108.2 = $104for_iter.3  :: float64
        #   del $104for_iter.3
        #   branch $104for_iter.4, 108, 158
        # label 108
        #   del $104for_iter.4
        #   c = $phi108.2  :: float64
        #   del $phi108.2
        # label 158

        for c in coeffs:

            # --- LINE 11 --- 
            #   $114binary_op.6 = getitem(value=x, index=i, fn=<built-in function getitem>)  :: float64
            #   $binop_mul126.7 = acc.2 * $114binary_op.6  :: float64
            #   del $114binary_op.6
            #   acc.1 = $binop_mul126.7 + c  :: float64
            #   del c
            #   del $binop_mul126.7
            #   acc.2 = acc.1  :: float64
            #   del acc.1
            #   jump 104

            acc = acc * x[i] + c

        # --- LINE 12 --- 
        #   del $phi108.2
        #   del $phi104.1
        #   del $104for_iter.4
        #   out[i] = acc.2  :: (Array(float64, 1, 'C', False, aligned=True), int64, float64) -> none
        #   del i
        #   del acc.2
        #   jump 90

        out[i] = acc

    # --- LINE 13 --- 
    #   del x
    #   del $phi94.1
    #   del $phi90.0
    #   del $90for_iter.3
    #   $180return_value.3 = cast(value=out)  :: array(float64, 1d, C)
    #   del out
    #   return $180return_value.3

    return out


================================================================================

Two things to read out of that dump:

  • freevar(coeffs: (1.0, -3.0, ...)) — the entire tuple, inlined into the IR as a constant. Its type is UniTuple(float64 x 8), and in numba a tuple’s length is part of its type. The compiler therefore knows the trip count.
  • Because the trip count is known, for c in coeffs is not a loop in the compiled code at all. Numba fully unrolls iteration over a tuple — there is no loop variable, no bounds test, and the eight coefficients appear as immediate operands.

Which is visible by just counting arithmetic in the generated LLVM IR — the same tour taken in the intro notebook, now used as a measurement rather than a sightseeing trip:

import re


def describe_codegen(name, dispatcher):
    ir = list(dispatcher.inspect_llvm().values())[0]
    asm = list(dispatcher.inspect_asm().values())[0]
    vector_types = sorted(set(re.findall(r"<\d+ x double>", ir)))
    print(f"{name}:")
    print(f"  LLVM IR      : {ir.count('fmul')} fmul, {ir.count('fadd')} fadd")
    print(f"  vector types : {vector_types or 'none — scalar only'}")
    print(f"  x86 multiplies: {asm.count('mulsd')} scalar (mulsd), {asm.count('vmulpd')} packed (vmulpd)")


describe_codegen("runtime coefficients", horner_runtime)
describe_codegen("baked coefficients  ", horner_baked)
runtime coefficients:
  LLVM IR      : 9 fmul, 9 fadd
  vector types : none — scalar only
  x86 multiplies: 9 scalar (mulsd), 0 packed (vmulpd)
baked coefficients  :
  LLVM IR      : 48 fmul, 48 fadd
  vector types : ['<8 x double>']
  x86 multiplies: 40 scalar (mulsd), 8 packed (vmulpd)

The runtime version emits one multiply-add per loop body and works entirely in scalar registers: mulsd is “multiply one double”. Nothing was vectorised, because LLVM cannot widen a loop whose inner trip count it does not know.

The baked version emits several times as much arithmetic — the eight-step Horner chain written out straight-line — and operates on <8 x double>: eight polynomial evaluations in flight at once, one AVX-512 register wide. That is the third win. With the inner loop gone, the outer loop over i is a flat uniform block, which is exactly the shape a vectoriser can transform. The extra instructions are not extra work; they are the same work, done eight points at a time. (The scalar multiplies that remain in the baked version are the remainder loop — the last few points that do not fill a vector register.)

So the chain is: a Python value becomes a numba type → the type fixes the trip count → the loop unrolls → the surrounding loop vectorises. Only the first link involved metaprogramming. The rest is a normal optimising compiler finally being given enough information to do its job.

The two stages, made visible

It is easy to lose track of which code runs when, so make the seam audible:

def make_horner_loud(coeffs):
    print(f"  stage 1 (host Python): generating a kernel for {len(coeffs)} coefficients")
    coeffs = tuple(coeffs)

    @jit("f8[::1](f8[::1])", nopython=True, nogil=True)
    def horner(x):
        out = np.empty_like(x)
        for i in range(x.size):
            acc = 0.0
            for c in coeffs:
                acc = acc * x[i] + c
            out[i] = acc
        return out

    print("  stage 1 done: machine code exists")
    return horner


print("calling the generator:")
t0 = time.perf_counter()
loud = make_horner_loud(COEFFS)
compile_time = time.perf_counter() - t0
print(f"generation took {compile_time:.2f} s")

print("\ncalling the generated kernel (stage 2 — no Python involved):")
t0 = time.perf_counter()
loud(x)
print(f"call took {(time.perf_counter() - t0) * 1e3:.1f} ms")
calling the generator:
  stage 1 (host Python): generating a kernel for 8 coefficients
  stage 1 done: machine code exists
generation took 0.04 s

calling the generated kernel (stage 2 — no Python involved):
call took 0.5 ms

The prints fire once, during generation; the compiled kernel never touches them. That is the whole trick, and also the whole bill: one compilation per distinct configuration. A different coefficient list is a different program, with its own compile.

That cost is real and it compounds — it is why this pattern belongs in library code, where a handful of configurations are set up once and used for the rest of the run, and not in a hot path that keeps inventing new ones.

t0 = time.perf_counter()
family = [make_horner([1.0] * n) for n in (2, 4, 8, 16)]
print(f"four configurations: {time.perf_counter() - t0:.2f} s of compilation, once")
print(f"one shared source, {len({id(f) for f in family})} distinct machine-code kernels,")
print(f"all called {family[0].__name__!r} -- the name is the source's, the code is per-configuration")
four configurations: 0.13 s of compilation, once
one shared source, 4 distinct machine-code kernels,
all called 'horner' -- the name is the source's, the code is per-configuration

Why this is more than constant folding

Baking in numbers is the easy half. The important half is that stage 1 is all of Python, so the constants can be computed by code that numba could never compile.

Take finite-difference stencils. The weights for an order-th derivative on a symmetric grid come from solving a small Vandermonde system, and doing it in floating point loses digits exactly where accuracy matters. In stage 1 that is a non-issue — solve it in exact rational arithmetic with fractions.Fraction, a pure-Python class numba has never heard of:

from fractions import Fraction
from math import factorial


def fd_weights(offsets, order):
    """Exact finite-difference weights for the `order`-th derivative, by Gaussian elimination
    over the rationals.

    Solves sum_j w_j * offset_j**k = order! * delta(k, order) for k = 0 .. n-1.
    """
    n = len(offsets)
    rows = [
        [Fraction(o) ** k for o in offsets] + [Fraction(factorial(order) if k == order else 0)]
        for k in range(n)
    ]
    for i in range(n):
        pivot = next(r for r in range(i, n) if rows[r][i])
        rows[i], rows[pivot] = rows[pivot], rows[i]
        rows[i] = [v / rows[i][i] for v in rows[i]]
        for r in range(n):
            if r != i and rows[r][i]:
                factor = rows[r][i]
                rows[r] = [a - factor * b for a, b in zip(rows[r], rows[i])]
    return [rows[i][n] for i in range(n)]


print("second derivative, 5-point stencil:", fd_weights([-2, -1, 0, 1, 2], 2))
print("first derivative, 3-point stencil :", fd_weights([-1, 0, 1], 1))
second derivative, 5-point stencil: [Fraction(-1, 12), Fraction(4, 3), Fraction(-5, 2), Fraction(4, 3), Fraction(-1, 12)]
first derivative, 3-point stencil : [Fraction(-1, 2), Fraction(0, 1), Fraction(1, 2)]

Fraction(-1, 12), not -0.08333333333333333. Exact, and derived rather than copied out of a textbook — so a stencil of any width and any derivative order is one function call away.

Now feed that to the code generator. The rationals are converted to floats at the last possible moment, and the grid spacing is folded in at the same time, so the kernel contains one fused constant per tap instead of a division per point:

def make_stencil(order, half_width, dx):
    """Compile an `order`-th derivative operator on a uniform grid of spacing `dx`."""
    offsets = range(-half_width, half_width + 1)
    weights = tuple(float(w) / dx**order for w in fd_weights(list(offsets), order))

    @jit("f8[::1](f8[::1])", nopython=True, nogil=True)
    def stencil(u):
        """Apply the compiled stencil to `u`, returning a new array."""
        out = np.zeros_like(u)
        for i in range(half_width, u.size - half_width):
            acc = 0.0
            for k in range(-half_width, half_width + 1):
                acc += weights[k + half_width] * u[i + k]
            out[i] = acc
        return out

    return stencil


dx = 1e-3
grid = np.arange(0.0, 1.0, dx)
u = np.sin(2 * np.pi * grid)

d2 = make_stencil(order=2, half_width=2, dx=dx)
interior = slice(2, -2)
error = np.abs(d2(u)[interior] - (-((2 * np.pi) ** 2) * u[interior])).max()
print(f"max error against the analytic second derivative: {error:.2e}")
max error against the analytic second derivative: 1.76e-09

Note what got baked in: half_width is a freevar too, so the loop bounds are constants, not just the weights. The inner loop unrolls for the same reason the Horner chain did, and the boundary offsets become immediate addresses. Against the same kernel with the weights passed in as an array:

@jit("f8[::1](f8[::1], f8[::1])", nopython=True, nogil=True)
def stencil_runtime(u, weights):
    half = weights.size // 2
    out = np.zeros_like(u)
    for i in range(half, u.size - half):
        acc = 0.0
        for k in range(-half, half + 1):
            acc += weights[k + half] * u[i + k]
        out[i] = acc
    return out


weights_array = np.array([float(w) / dx**2 for w in fd_weights([-2, -1, 0, 1, 2], 2)])
np.testing.assert_allclose(d2(u), stencil_runtime(u, weights_array))

baked = timeit(d2, u)
runtime = timeit(stencil_runtime, u, weights_array)
print(f"baked stencil  : {baked * 1e6:.1f} us")
print(f"runtime weights: {runtime * 1e6:.1f} us  ({runtime / baked:.1f}x slower)")
baked stencil  : 1.2 us
runtime weights: 2.4 us  (2.0x slower)

Stage 2: the configuration wants to be an object

make_stencil(order, half_width, dx) has three parameters that always travel together, and real code needs more than one operator over the same grid — a first derivative, a second derivative, a Laplacian, each sharing dx. That is a class.

The obvious first attempt is a method that returns a kernel:

from dataclasses import dataclass


@dataclass
class NaiveGrid:
    dx: float

    def derivative(self, order, half_width):
        return make_stencil(order, half_width, self.dx)


naive = NaiveGrid(dx=dx)
print("works, but reads badly:", naive.derivative(2, 2)(u)[interior][:3])
works, but reads badly: [-0.49608737 -0.74410657 -0.9920964 ]

Two problems, one cosmetic and one fatal. The call site obj.derivative(2, 2)(u) has a double-call shape that advertises the implementation instead of the intent. And far worse, every call recompiles — derivative runs make_stencil afresh each time, so a full compilation hides inside what looks like a method call, and it never gets cheaper:

for attempt in (1, 2, 3):
    t0 = time.perf_counter()
    naive.derivative(2, 2)(u)
    print(f"call {attempt}: {(time.perf_counter() - t0) * 1e3:.0f} ms")

print(f"the kernel itself takes {timeit(make_stencil(2, 2, dx), u) * 1e6:.1f} us")
call 1: 39 ms
call 2: 39 ms
call 3: 41 ms
the kernel itself takes 1.2 us

functools.cached_property fixes both at once. The property body is the generator; the value it caches is the compiled kernel; and because attribute access returns the kernel itself, the trailing (u) is just calling it:

from functools import cached_property


@dataclass(frozen=True)
class Grid:
    """A uniform 1-D grid that compiles its own differential operators."""

    dx: float

    @cached_property
    def d2(self):
        """Second derivative, 4th-order accurate, over the interior of `u`."""
        return make_stencil(order=2, half_width=2, dx=self.dx)

    @cached_property
    def d1(self):
        """First derivative, 2nd-order accurate, over the interior of `u`."""
        return make_stencil(order=1, half_width=1, dx=self.dx)


g = Grid(dx=dx)
print("reads like a method:", g.d2(u)[interior][:3])
print(f"and stays fast: {timeit(g.d2, u) * 1e6:.1f} us per call")
reads like a method: [-0.49608737 -0.74410657 -0.9920964 ]
and stays fast: 2.2 us per call

This is the pattern in full. It reads like an ordinary object with ordinary methods; underneath, each “method” is a separately compiled program specialised to that instance’s configuration.

It is worth saying plainly why the caching has to be there and not, say, in an __init__ that compiles everything up front: a class may expose a dozen operators and a given script uses two. cached_property gives pay-per-use compilation — nothing is compiled until asked for, and nothing is compiled twice.

frozen=True is not decoration

The frozen=True is load-bearing, and it is where a functional-programming idea earns its keep inside a Python class.

A generator reads self at compile time and bakes what it finds into machine code. In a mutable class that is a bug waiting to happen: assign to g.dx after the first access and the object and its kernels disagree for ever, silently, with no error and no way to notice. The cache is only valid as long as the thing it was derived from does not change — so make it unable to change:

from dataclasses import FrozenInstanceError

try:
    g.dx = 999.0
except FrozenInstanceError as e:
    print("mutation refused:", type(e).__name__, e)
mutation refused: FrozenInstanceError cannot assign to field 'dx'

That reframes the whole pattern. The instance is no longer an object with state — it is a value, and each @cached_property is a pure function of that value. Caching a pure function of an immutable value is just memoisation, and memoisation is always sound: the expression g.d2 is referentially transparent, so evaluating it once and reusing the answer cannot change the program’s meaning. That is the entire correctness argument for the pattern, and frozen=True is what makes it true rather than merely hoped for.

One nice surprise falls out of the standard library: cached_property still works on a frozen dataclass, even though the instance refuses attribute assignment. It writes into obj.__dict__ directly rather than going through __setattr__, so the dataclass’s mutation guard never sees it:

print("dx is immutable, but the cache was still written:", "d2" in vars(g))
print("cached kernel:", type(vars(g)["d2"]).__name__)
dx is immutable, but the cache was still written: True
cached kernel: CPUDispatcher

Peeling the illusion: g.d2(u) is not a method call

The syntax g.d2(u) is identical to a method call, but the machinery is different, and the difference leaks in ways that matter once other people — or other tools — have to use the class. Start with the bytecode, which is where the two are still indistinguishable:

dis.dis(lambda g, u: g.d2(u))
  1           RESUME                   0
              LOAD_FAST_BORROW         0 (g)
              LOAD_ATTR                1 (d2 + NULL|self)
              LOAD_FAST_BORROW         1 (u)
              CALL                     1
              RETURN_VALUE

LOAD_ATTR then CALL — exactly what a real method call compiles to. The divergence is entirely at run time, in what LOAD_ATTR does:

  • real method: finds a function on the class, and the interpreter’s method-call fast path calls it with g prepended as self. One object, shared by every instance.
  • this: finds a cached_property descriptor on the class, runs its __get__, which on first access compiles a program, stores it in g.__dict__, and returns it. self is consumed at generation time and never reaches the call.

So the first thing to be honest about: this is not a method that happens to be fast. It is a per-instance function object, and self is a compile-time input — which is exactly the reason frozen=True was not optional.

What survives

Less is broken than one might fear, and it is worth checking rather than assuming. Numba’s @jit applies functools.wraps to the dispatcher, so the compiled object is not an opaque blob:

import inspect
import pickle

print("inspect.signature :", inspect.signature(g.d2))
print("getsource works   :", inspect.getsource(g.d2).splitlines()[0].strip())
print("pickle roundtrip  :", pickle.loads(pickle.dumps(g)).d2(u)[interior][0])
print("per-call overhead : none — after the first access it is a plain instance-dict lookup")
inspect.signature : (u)
getsource works   : @jit("f8[::1](f8[::1])", nopython=True, nogil=True)
pickle roundtrip  : -0.49608737014023063
per-call overhead : none — after the first access it is a plain instance-dict lookup

Signature, source, and even pickling for multiprocessing all work, and — because cached_property writes into g.__dict__ and is shadowed from then on — there is no per-call descriptor overhead. So the usual worry, “you lose introspection”, is too broad.

What leaks

What actually breaks is narrower and more specific. Five things:

# 1. The object answers to the wrong identity: it is the *generator's* inner function, and every
#    method built by the same generator is therefore indistinguishable from every other.
print("1. type of g.d2:", type(g.d2).__name__)
for name in ("d2", "d1"):
    kernel = getattr(g, name)
    print(f"   g.{name}.__name__ = {kernel.__name__!r}, __doc__ = {kernel.__doc__!r}")
print("   the docstrings you wrote live on the class:")
for name in ("d2", "d1"):
    print(f"     Grid.{name}.__doc__ = {getattr(Grid, name).__doc__!r}")
1. type of g.d2: CPUDispatcher
   g.d2.__name__ = 'stencil', __doc__ = 'Apply the compiled stencil to `u`, returning a new array.'
   g.d1.__name__ = 'stencil', __doc__ = 'Apply the compiled stencil to `u`, returning a new array.'
   the docstrings you wrote live on the class:
     Grid.d2.__doc__ = 'Second derivative, 4th-order accurate, over the interior of `u`.'
     Grid.d1.__doc__ = 'First derivative, 2nd-order accurate, over the interior of `u`.'
# 2. The class attribute is a descriptor object, not a function.
print("2. callable(Grid.d2):", callable(Grid.d2), "-- type:", type(Grid.d2).__name__)
try:
    Grid.d2(g, u)
except TypeError as e:
    print("   Grid.d2(g, u) ->", type(e).__name__, e)
2. callable(Grid.d2): False -- type: cached_property
   Grid.d2(g, u) -> TypeError 'cached_property' object is not callable
# 3. Merely *looking* compiles: attribute access has a side effect measured in milliseconds.
fresh = Grid(dx=dx)
t0 = time.perf_counter()
fresh.d2  # no call -- just touching the name
cold = time.perf_counter() - t0
t0 = time.perf_counter()
fresh.d2
warm = time.perf_counter() - t0
print(f"3. first access: {cold * 1e3:.0f} ms, second access: {warm * 1e6:.1f} us")
print(f"   ({cold / warm:,.0f}x — the first one ran a compiler)")
3. first access: 43 ms, second access: 17.3 us
   (2,499x — the first one ran a compiler)
# 4. repr leaks the implementation.
print("4.", repr(g.d2))
4. CPUDispatcher(<function make_stencil.<locals>.stencil at 0x14a68425d900>)
# 5. cached_property needs a per-instance __dict__.
class SlottedGrid:
    __slots__ = ("dx",)

    def __init__(self, dx):
        self.dx = dx

    @cached_property
    def d2(self):
        return make_stencil(order=2, half_width=2, dx=self.dx)


try:
    SlottedGrid(dx).d2
except TypeError as e:
    print("5. __slots__ ->", type(e).__name__, e)
5. __slots__ -> TypeError No '__dict__' attribute on 'SlottedGrid' instance to cache 'd2' property.

Numbers 1 and 3 are the ones that bite day to day, and they compound each other. In a notebook or an IDE, inspecting an object is supposed to be free and informative. Here it is neither: g.d2? stalls to run a compiler, and then reports a function called stencil — the same name and the same docstring g.d1? reports, because both are closures from inside the one make_stencil generator. The two methods are genuinely different machine code and completely indistinguishable to introspection. Hovering in an editor, a debugger rendering the variables pane, vars(g) in a log line, a repr in a traceback — every one of them pays the compile and gets the wrong answer.

Number 2 bites in library design: Grid.d2 is not callable, so the “method” cannot be passed around unbound, cannot be wrapped by a class-level decorator, and help(Grid) files it under readonly properties rather than methods. A type checker sees a property returning CPUDispatcher and cannot tell callers what arguments to pass.

All of these are problems in Python’s object model, not in the generated code — the machine code is exactly as good as it was. Which means they are fixable in Python’s object model.

Making it feel native: a descriptor plus a proxy

Two mechanisms fix all of this, and both are ordinary Python.

The first is a descriptor: any object with __get__ participates in attribute lookup. cached_property is one; so is property; so, in fact, is every plain function, which is how self gets bound in the first place. Writing one is not exotic — it is the supported way to say “attribute access means something particular here”.

The second is a transparent proxy: an object that stands in front of another and forwards everything. Writing a good one by hand is genuinely hard — __class__, comparisons, numeric dunders, copy, pickle all have to be dealt with individually — which is why wrapt exists. It is the library behind most well-behaved Python decorators, and wrapt.LazyObjectProxy is precisely the piece we need: a proxy that takes a factory and does not call it until the wrapped object is first touched.

So: a descriptor to intercept g.d2, and a lazy proxy to defer the compile until something actually uses the kernel.

import copy
import functools

import wrapt


class jitmethod:
    """Like `cached_property`, but for factories that return a compiled kernel.

    Decorates a method whose body generates and returns a jitted function. The kernel is compiled
    on first use, once per instance, and the object handed back impersonates a bound method.
    """

    def __init__(self, factory):
        self.factory = factory
        functools.update_wrapper(self, factory)  # __name__, __qualname__, __doc__, __module__

    def __set_name__(self, owner, name):
        self.attrname = name

    def __get__(self, obj, objtype=None):
        if obj is None:
            return self  # class access: hand back something callable and documented
        bound = BoundJitMethod(self, obj)
        obj.__dict__[self.attrname] = bound  # non-data descriptor: shadowed from here on
        return bound

    def __call__(self, obj, *args, **kwargs):
        return getattr(obj, self.attrname)(*args, **kwargs)  # honour the per-instance cache


class BoundJitMethod(wrapt.LazyObjectProxy):
    """A lazily compiled kernel that impersonates a bound method of `obj`."""

    def __new__(cls, descriptor, obj):
        return super().__new__(cls, None)  # LazyObjectProxy.__new__ takes one argument

    def __init__(self, descriptor, obj):
        super().__init__(lambda: descriptor.factory(obj))  # not called until first touch
        self._self_descriptor = descriptor  # wrapt reserves the `_self_` prefix for proxy state
        self._self_obj = obj

    def __call__(self, *args, **kwargs):
        return self.__wrapped__(*args, **kwargs)  # this is what triggers the compile

    @property
    def __name__(self):
        return self._self_descriptor.__name__  # the attribute's name, not the kernel's

    def __repr__(self):
        state = "compiled" if self.__wrapped_get_called__ else "not compiled yet"
        return f"<jit method {self._self_descriptor.__qualname__} of {self._self_obj!r} [{state}]>"

    def __reduce__(self):
        return (getattr, (self._self_obj, self._self_descriptor.attrname))

    def __deepcopy__(self, memo):
        return getattr(copy.deepcopy(self._self_obj, memo), self._self_descriptor.attrname)

    def __copy__(self):
        return getattr(copy.copy(self._self_obj), self._self_descriptor.attrname)

What each piece is doing:

  • __get__ writes the bound proxy into obj.__dict__. Because jitmethod defines no __set__, it is a non-data descriptor, which ranks below the instance dictionary in attribute lookup — so every subsequent g.d2 is a plain dict hit and skips the descriptor entirely. That is the identical trick cached_property uses, and it is why neither costs anything per call.
  • wrapt.LazyObjectProxy supplies everything below __call__: the whole dunder surface, __class__ forwarding (so isinstance against the dispatcher is true), and attribute forwarding, all without us enumerating it. Only the attributes we deliberately override — __name__, __repr__ — do not reach the kernel, and those are exactly the ones that must not trigger a compile.
  • The _self_ prefix is wrapt’s convention: attributes named that way are stored on the proxy; everything else would be set on the wrapped object.
  • __reduce__, __copy__ and __deepcopy__ are required rather than optional — wrapt raises NotImplementedError rather than silently copying a proxy wrong. All three say the same thing: the method is not a value to be copied; it is an attribute of its owner, so rebuild it by looking it up on the (copied) owner.

The class body now looks the same as before, one decorator apart:

@dataclass(frozen=True)
class NativeGrid:
    """A uniform 1-D grid that compiles its own differential operators."""

    dx: float

    @jitmethod
    def d2(self):
        """Second derivative, 4th-order accurate, over the interior of `u`."""
        return make_stencil(order=2, half_width=2, dx=self.dx)

    @jitmethod
    def d1(self):
        """First derivative, 2nd-order accurate, over the interior of `u`."""
        return make_stencil(order=1, half_width=1, dx=self.dx)


ng = NativeGrid(dx=dx)

Re-run the same probes:

t0 = time.perf_counter()
ng.d2  # identity and access cost, before anything has been compiled
access = time.perf_counter() - t0
print("1. names are per method:", ng.d2.__name__, "/", ng.d1.__name__)
print("2. callable(NativeGrid.d2):", callable(NativeGrid.d2))
print(f"3. bare attribute access: {access * 1e6:.0f} us — nothing compiled yet")
print("4.", repr(ng.d2))
1. names are per method: d2 / d1
2. callable(NativeGrid.d2): True
3. bare attribute access: 63 us — nothing compiled yet
4. <jit method NativeGrid.d2 of NativeGrid(dx=0.001) [not compiled yet]>
print("   unbound call works:", NativeGrid.d2(ng, u)[interior][0])
print("4. after the first call:", repr(ng.d2))
   unbound call works: -0.49608737014023063
4. after the first call: <jit method NativeGrid.d2 of NativeGrid(dx=0.001) [compiled]>

The two methods now report their own names, inspection is free, the repr says what the object is and whether it has been compiled yet, and the class attribute is a callable taking self first — a method in every respect that help, a type checker, or a class-level decorator cares about. And because the proxy is transparent rather than hand-rolled, more works than before:

print("inspect.signature :", inspect.signature(ng.d2))
print("__class__ forwards:", ng.d2.__class__.__name__)
print("isinstance passes :", isinstance(ng.d2, type(g.d2)))  # type(g.d2) is CPUDispatcher
print("dispatcher attrs  :", ng.d2.nopython_signatures)
print("pickle roundtrip  :", pickle.loads(pickle.dumps(ng)).d2(u)[interior][0])
print("deepcopy roundtrip:", copy.deepcopy(ng).d2(u)[interior][0])
np.testing.assert_allclose(ng.d2(u), g.d2(u))
print(f"same numbers, same speed: {timeit(ng.d2, u) * 1e6:.1f} us per call")
inspect.signature : (u)
__class__ forwards: CPUDispatcher
isinstance passes : True
dispatcher attrs  : [(Array(float64, 1, 'C', False, aligned=True),) -> array(float64, 1d, C)]
pickle roundtrip  : -0.49608737014023063
deepcopy roundtrip: -0.49608737014023063
same numbers, same speed: 1.4 us per call

isinstance(ng.d2, CPUDispatcher) being true is the clearest sign of what wrapt bought: the proxy forwards __class__ itself, so code that type-checks the kernel cannot tell it is talking to a stand-in. The hand-rolled __getattr__ version could never manage that.

Three limitations remain, and they are inherent rather than sloppy.

Transparency and laziness pull against each other. Every attribute the proxy forwards is an attribute that materialises the kernel. inspect.signature(ng.d2) therefore compiles — the parameter names live in the generated function, and there is no generated function until something generates it. That is the honest shape of code generation; a C++ template has the same property. __doc__ is the same story with a twist: wrapt forwards it below the Python level, so it cannot be overridden on the proxy at all. The right response is not to fight it but to document the kernel — give the generated function a docstring, which numba copies onto the dispatcher — and leave the method-level docstring on the class, where help(NativeGrid) and NativeGrid.d2? find it for free:

print("class level (free)   :", inspect.getdoc(NativeGrid.d2))
print("instance level (kernel):", inspect.getdoc(ng.d2))
class level (free)   : Second derivative, 4th-order accurate, over the interior of `u`.
instance level (kernel): Apply the compiled stencil to `u`, returning a new array.

__slots__ is still out, for the same reason as before: the per-instance cache has to live somewhere, and that somewhere is obj.__dict__. A side table keyed by instance would lift the restriction at the cost of tying object lifetimes to the cache.

wrapt.LazyObjectProxy builds a class per instance — that is how it decides which dunder methods to synthesise — so a bound method costs more memory than a plain function would. For a handful of kernels per object this is irrelevant; for millions of proxies it would not be, and wrapt’s own documentation points at BaseObjectProxy for that case.

The payoff of freezing: memoisation across instances

cached_property and jitmethod both cache per instance. Two Grid(dx=1e-3) objects are two separate caches and therefore two separate compiles of byte-identical machine code. In a script that constructs its configuration objects in a loop, or in a test suite, that is pure waste.

Immutability removes the obstacle. A frozen dataclass with eq=True — the default — gets both __eq__ and __hash__ generated, so the configuration is not just conceptually a value, it is a usable dictionary key:

a, b = NativeGrid(dx=2e-3), NativeGrid(dx=2e-3)
print("distinct objects:", a is not b, "| equal:", a == b, "| same hash:", hash(a) == hash(b))
distinct objects: True | equal: True | same hash: True

And the generator is a pure function of its arguments, so it can simply be memoised. One line, no new machinery — functools.lru_cache is the same memoisation argument applied one level up:

from functools import lru_cache

make_stencil = lru_cache(maxsize=None)(make_stencil)

t0 = time.perf_counter()
a.d2(u)
first = time.perf_counter() - t0

t0 = time.perf_counter()
b.d2(u)
second = time.perf_counter() - t0

print(f"first instance : {first * 1e3:6.1f} ms  (compiled)")
print(f"second instance: {second * 1e3:6.1f} ms  (cache hit)")
print("literally the same machine code:", a.d2.__wrapped__ is b.d2.__wrapped__)
first instance :   40.4 ms  (compiled)
second instance:    0.1 ms  (cache hit)
literally the same machine code: True

Three caches are now stacked, and each one is justified by immutability at a different level: lru_cache keyed on the generator’s arguments, the per-instance obj.__dict__ entry, and numba’s own dispatcher cache keyed on argument types. None of them can go stale, because nothing any of them derives from can change.

Two caveats worth stating. lru_cache(maxsize=None) never evicts, so a program that really does invent configurations forever will grow without bound — maxsize exists for that. And a frozen dataclass is only hashable if its fields are: put a NumPy array in one and hash() raises. If a configuration genuinely needs array-valued parameters, key the cache on something hashable derived from them (array.tobytes(), a shape-and-dtype tuple) rather than on the object.

What this pattern is, generally

Strip away numba and the shape is familiar: a program that writes a program, with a boundary between the two chosen so that everything known early is compiled away. The same idea appears throughout scientific computing under different names.

  • C++ templates. std::array<double, 8> unrolls for the same reason UniTuple(float64 x 8) does — the length is in the type. Template metaprogramming is C++’s answer to the same question, with a far worse metalanguage: the “stage 1 language” is the template system itself, which is why Python-as-metalanguage feels so pleasant by comparison.
  • JAX. jax.jit traces a Python function, and anything not a traced array becomes a constant in the jaxpr; static_argnums is a declaration of which arguments belong to stage 1. Same boundary, drawn explicitly instead of via closures.
  • Loop tiling and autotuning libraries (FFTW’s planner, ATLAS, Halide’s schedules) generate specialised kernels at setup time for the same reason: the shape is known before the data is.
  • Even functools.partial is the degenerate case — fixing arguments early — minus the compiler that could exploit it.

What numba adds is that the metalanguage and the object language are the same syntax, so the boundary is invisible. That is the pattern’s greatest strength and its main hazard, and the working rules follow from it:

  • Put the boundary where the information is. Anything fixed for the lifetime of the object — grid spacing, stencil width, model choice, a flag that selects a branch — belongs in stage 1. Anything that varies per call belongs in the signature.
  • Count your configurations. Each one is a compile and a copy of the machine code. Dozens is fine; a fresh one per iteration is a bug.
  • Freeze the configuration. self is a compile-time input, so a mutable configuration object is a cache invalidation problem with no invalidation mechanism. frozen=True turns the object into a value, which makes every cache in the stack a memoisation of a pure function — sound by construction rather than by discipline, and hashable into the bargain.
  • Fix the ergonomics once. The costs of the class pattern are all in attribute lookup, and attribute lookup is programmable. A descriptor plus wrapt.LazyObjectProxy buys back the entire native feel in about thirty lines, written once per project, not once per method.