Every data scientist eventually hits the same wall. You write a filter like (a > 0) & (b < 1) over a ten-million-element NumPy array, and Python does something quietly devastating: it allocates a full temporary boolean array for a > 0, another for b < 1, and a third for the &. Three passes over memory for an expression that, on a modern CPU, should stream through cache once. Multiply that by every chunk in a loop, and your supposedly vectorized code spends most of its time in the memory allocator rather than in arithmetic.

Numexpr attacks this from an unexpected angle. Instead of making NumPy smarter, it treats your expression string as a tiny compiled language: parse it, type-check it, lower it to a compact instruction encoding, and run it on a small C++ virtual machine that reads inputs through NumPy’s own iterators, blocking the work into cache-sized chunks. When you call pandas.eval() on a compatible expression and the speedup appears out of nowhere, this machinery is what you are actually hitting. The project is small enough to read in an afternoon — roughly six thousand lines across its Python front-end and C++ back-end — but it contains a complete compiler and a complete executor, wired end to end.

This post is a source tour of the current master tree (version 2.14.3.dev0, default branch master). Every file, symbol and line number below was verified against the real repository, so you can click through and follow along in the code itself.

Numexpr architecture overview: public API, compiler front-end, bytecode tables, virtual machine core and the pthread worker pool

The whole system in five stages: a string from evaluate() becomes an expression tree, then typed four-byte bytecode, then block-processed iterations inside a C extension that owns a persistent thread pool.

Reading the overview from left to right:

  • evaluate, L1055 — the public entry point checks two per-thread caches of size 256 before doing any recompilation, so repeating the same expression with new array values costs only a VM call.
  • getType, L819 — each operand’s dtype.kind is mapped to a VM kind; itemsize decides int32 versus int64 and float32 versus double, and a Unicode dtype is rejected outright with a ValueError.
  • _sanitize_expression, L342 — because the front-end later calls eval, the string is first walked through a whitelist of exactly 40 allowed AST node types, with dunder names and unexpected attributes rejected.
  • typeCompileAst, L196 — the typed instruction is found by enumerating upcast permutations of the argument typecodes until something like add_ddd exists in the opcode table, inserting explicit cast nodes when inputs must be widened.
  • collapseDuplicateSubtrees, L509 — common subexpressions are collapsed into alias nodes sharing one register, before optimizeTemporariesAllocation, L532 recycles dead temporaries to minimize scratch buffers.
  • compileThreeAddrForm, L613 — the final encoding packs each instruction into exactly four bytes: one opcode byte plus destination and two register bytes, with 0xff marking an absent operand.
  • binop, L165 — constant folding happens while nodes are being built, not in a separate pass: if both operands are constants, the operator executes immediately in Python and the AST never sees it.
  • NumExpr_run, L1044 — the C entry point binds operands through NumPy iterators, detects a final reduction by testing last_opcode > OP_REDUCTION, then chooses serial or parallel execution.
  • vm_engine_iter_task, L674 — the executor iterates blocks and specializes the compile-time block size first; the source comment notes this distinction alone is worth 30–50% on some tests.
Numexpr detail diagram: front-end lowering, expression algebra, opcode and function tables, VM core, threading and configuration

The detail view adds the lowering steps, the two lookup tables, the reduction gate, the string kernels and the fork-aware thread pool.

The front-end is a real compiler, just a small one

The Python side lives in two files. expressions.py (546 lines) implements the lazy algebra: the E object fabricates a VariableNode for any attribute you touch, and operator overloads record the tree shape. Because the operators are intercepted, arithmetic on constants folds immediately — where() with a constant condition even prunes the untaken branch. Two rewrites stand out as deliberate performance engineering. Division by a float or complex constant under moderate or aggressive optimization becomes multiplication by the reciprocal, saving a slow divide per lane. Exponentiation goes further: with optimization='aggressive', integral and half-integral exponents in the range −50 to 50 are expanded into multiplication trees via binary exponentiation, with the half-integer tail handled by a sqrt and negative exponents by a reciprocal.

necompiler.py (1200 lines) then does the lowering. Names are resolved by compiling the string with compile(), then evaluating it with empty builtins while each name binds to a typed VariableNode — a trick that turns Python’s own parser into the expression parser for free. The typed-code selection in sigPerms walks upcast permutations over the letters bilfdc (bool, int, long, float, double, complex), and strings are deliberately never upcast to numbers. If no plain opcode matches, a generic func_*n row is used with the function code smuggled in as an immediate operand. Register assignment is textbook: leaves first, branch temporaries second, with common-subexpression aliases and the temporary-reuse pass keeping the register file tight, and disassemble() can print the program back out by reversing the opcode table.

147 opcodes and a 1024-lane block

The instruction set is a single X-macro table in opcodes.hpp: rows numbered 0 through 146, from noop and typed copies through casts, comparisons per type pair, arithmetic, where, string operations, generic function calls and reductions. Two structural constraints matter. First, one byte per opcode means the format caps at 255 rows, which the table’s closing comment anticipates. Second, reductions (sum, prod, min, max, rows 125–145) are forced to live after the OP_REDUCTION sentinel at 124, so the interpreter can tell whether a program ends in a reduction just by looking at the final opcode. The function table functions.hpp uses the same X-macro style, but each row names three implementations at once — the libm call, a Windows-safe variant, and the Intel VML kernel, e.g. sqrtf, sqrtf2, vsSqrt — and rounding goes through rintf specifically to match NumPy’s round-half-to-even.

Execution is where the design earns its speed. The block size BLOCK_SIZE1 is fixed at 1024 lanes, tuned on a Skylake E3-1245 v5, and the jump table in interp_body.cpp — 143 case OP_ handlers in 602 lines, self-described as a macro-heavy file included multiple times from interpreter.cpp — is recompiled under different BLOCK_SIZE macros so that fixed-size blocks become tight, unrolled loops while the ragged tail uses the variable-size expansion. Temporary registers are malloc‘d per block run, and string support includes a contains built on the two-way string-matching algorithm with separate short- and long-needle paths.

From a 40-node whitelist to a 64-thread ceiling: build facts

The numbers in this tree tell you a lot about how the system is budgeted:

  • 40 AST node types in the sanitizer whitelist, no more, and attribute access is limited to .real and .imag.
  • 147 opcodes total, with exactly 4 bytes per instruction and 255 as the hard encoding ceiling.
  • 1024 lanes per block, 64 as DEFAULT_MAX_THREADS, and NE_MAXARGS = 64 operands per call.
  • A 16-thread cap applied at startup on machines with more cores unless NUMEXPR_MAX_THREADS is set — a deliberate anti-oversubscription default for shared servers.
  • Compiled-expression caches sized at 256 entries each, evicting 10% of entries when full.
  • One persistent pthread pool per process, restarted automatically when the PID changes after a fork.

That last pair of numbers is worth dwelling on. pyproject-era projects usually rely on OpenMP or a thread pool library; numexpr hand-rolls its own. Workers are created once by init_threads(), blocked from inheriting signal dispositions via pthread_sigmask, and then parked on a condition-variable barrier. When a job arrives, the parallel engine sizes tasks as 16 * BLOCK_SIZE1 * nthreads so each worker receives roughly sixteen blocks — a compromise the code comments describe explicitly — hands each thread its own copy of the NumPy iterator, and releases the GIL for the whole computation. The barrier code loops on a barrier_passed flag to guard against spurious wakeups, citing a real issue number in the repository. On Windows the same pthread surface is emulated by a small win32/pthread.c that setup.py appends only for MSVC builds. Notably, the extension module is literally named numexpr.interpreter — there is no pure-Python interpreter.py; the opcode and funccode dictionaries you see on the Python side are built at PyInit_interpreter time by re-expanding the same headers, and the module declares itself GIL-free for the free-threaded CPython build.

The ecosystem context

This blocking-and-lowering strategy is the same core idea later generalized by the modern vectorized engines: Velox builds entire execution plans around cache-sized vector batches, and Polars implements an expression language that lowers to physical plans over columnar chunks, just as numexpr lowers an expression string to typed register code. And because the pandas eval path historically routes compatible expressions to numexpr when it is installed, frameworks that scale pandas across a cluster — Dask being the canonical example — inherit these speedups for free on each worker. A 2,000-line compiler plus a 1,600-line interpreter turned out to be a durable interface boundary for a whole ecosystem.

Honest Limits

The trade-offs are explicit in the code. Unicode arrays are not supported as a dtype — getType raises rather than converts. Only bytes strings work, and constants are ASCII-encoded. Python’s and, or and not are refused by design with a message pointing you to &, | and ~, because short-circuit semantics make no sense over arrays. A program can end in at most one reduction, and it must be the final opcode; constants must be scalars of the supported kinds; and expressions returning strings, dictionaries or arbitrary objects are out of scope entirely. The sanitizer defaults to on precisely because eval sits under the API, and disabling it via NUMEXPR_SANITIZE=0 is documented as an opt-in risk. VML acceleration only exists when the build finds MKL through site.cfg; the plain build dispatches through libm. None of these are bugs — they are the perimeter of a deliberately small language that made the whole system fast, auditable, and old enough to still run everywhere.

Watch PyShine on YouTube

Contents