import timeit
import numpy as np
from numba import jit, objmode
from scipy import optimizeThe previous notebook ended with np.einsum failing to compile and np.dot fixing it — a straightforward swap, because a supported vectorised replacement existed. That fix only works when the unsupported call was hiding a vectorised operation in the first place. Some computations are irreducibly scalar: no array-shaped version of them exists at all, in NumPy, SciPy, or Numba’s subset of either. numba.objmode is Numba’s answer to that case — a context manager that drops back into the real CPython interpreter for just the lines that need it, inside an otherwise nopython-compiled function.
The name of this notebook is also the caveat: objmode lets a function compile despite containing arbitrary, untypeable Python — but “compiles” and “is lowered to machine code” are not the same claim. Whatever runs inside an objmode block is not lowered at all; it stays exactly as slow as calling it from plain Python, every single time it executes. objmode is a guard that lets @jit(nopython=True) succeed at the boundary of what it can express, not a way to make unsupported code fast. The rest of this notebook makes that distinction concrete, by measuring it.
The task: Kepler’s equation, M = E - e·sin(E), solved for the eccentric anomaly E given a mean anomaly M and eccentricity e — the standard first step in turning “where is this planet in time” into “where is this planet in space.” There is no closed form for E; every orbit propagator solves it numerically, once per M, with a scalar root finder.
That last part is the point: scipy.optimize.brentq takes one scalar equation and one scalar bracket [a, b] and returns one scalar root. It has no array-input mode to fall back on — unlike, say, scipy.stats.norm.cdf, which already accepts whole arrays and would make “why not just vectorise it” an unanswerable objection. A whole array of mean anomalies genuinely has to be solved one M at a time, in a Python-level loop, no matter what calls it.
def kepler_equation(E, M, e):
return E - e * np.sin(E) - M
def kepler_python(M, e):
E = np.empty_like(M)
for i in range(M.shape[0]):
Mi = M[i]
E[i] = optimize.brentq(kepler_equation, Mi - 1.1, Mi + 1.1, args=(Mi, e))
return E
M = np.linspace(0.01, 2 * np.pi - 0.01, 2_000)
e = 0.7
E = kepler_python(M, e)
np.max(np.abs(E - e * np.sin(E) - M)) # residual of M = E - e·sin(E); should be ~1e-12np.float64(8.482103908136196e-13)
forceobj=True: compiling by giving up on typing entirely
Numba’s older, blunter escape hatch is to drop nopython=True and let the whole function compile in object mode — every operation dispatched through the CPython interpreter, the same as if @jit were never applied. It’s spelled forceobj=True (or, historically, just jit(...) with no nopython argument at all, which falls back to this silently rather than raising — one more reason to always pass nopython=True explicitly and let it fail loudly instead).
kepler_forceobj = jit(forceobj=True)(kepler_python)
kepler_forceobj(M, e)[:3]/tmp/ipykernel_550604/2719928597.py:5: NumbaWarning:
Compilation is falling back to object mode WITHOUT looplifting enabled because Function "kepler_python" failed type inference due to: Untyped global name 'kepler_equation': Cannot determine Numba type of <class 'function'>
File "../../../../../../../../../../../tmp/ipykernel_550604/2719928597.py", line 9:
<source missing, REPL/exec in use?>
def kepler_python(M, e):
array([0.03331895, 0.04374465, 0.05415929])
It compiles, and it runs. But check what actually got typed and lowered: nopython_signatures is the dispatcher’s own record of every signature it compiled to native code. For a pure object-mode function, that list is empty — nothing here was ever anything but interpreted Python wearing a @jit decorator.
print(f"forceobj nopython_signatures: {kepler_forceobj.nopython_signatures}")forceobj nopython_signatures: []
Object mode does have one trick up its sleeve: loop-lifting. If Numba can find a loop inside an object-mode function whose body happens to be fully typeable, it compiles just that loop in nopython mode and leaves the interpreted shell around it. Compiling kepler_python above actually triggers a NumbaWarning reporting that this loop-lifting attempt was tried here and failed — because the one loop in this function is where brentq(kepler_equation, ...) lives, and that’s exactly the part that isn’t typeable. There’s nothing left to lift out. Object mode falls back to interpreting the whole function, loop included, which is what the empty signature list above confirms directly.
objmode: doing by hand what loop-lifting couldn’t do automatically
Loop-lifting’s idea — compile what’s typeable, interpret what isn’t — is sound; it just couldn’t find a boundary here on its own, because the untypeable call sits inside the loop it would need to lift. objmode is that same idea with the boundary drawn by hand: keep nopython=True for the whole function — so everything outside the block is held to Numba’s full typing discipline — and name explicitly which lines, and which single expression’s type, get to opt out.
def kepler_objmode(M, e):
E = np.empty_like(M)
for i in range(M.shape[0]):
Mi = M[i]
with objmode(Ei="float64"):
Ei = optimize.brentq(kepler_equation, Mi - 1.1, Mi + 1.1, args=(Mi, e))
E[i] = Ei
return E
kepler_numba = jit(nopython=True)(kepler_objmode)
kepler_numba(M, e)[:3]array([0.03331895, 0.04374465, 0.05415929])
This time nopython=True doesn’t raise — the with objmode(Ei="float64"): block tells the compiler “trust me, whatever runs in here eventually produces a float64 named Ei; don’t try to type the inside of it.” Outside that block, kepler_objmode is ordinary nopython code: the for loop, the indexing into M and E, np.empty_like — all genuinely typed and compiled, which the non-empty signature list below confirms:
print(f"objmode nopython_signatures: {kepler_numba.nopython_signatures}")objmode nopython_signatures: [(Array(float64, 1, 'C', False, aligned=True), float64) -> array(float64, 1d, C)]
What the typed IR says about the boundary
inspect_types() makes the boundary explicit rather than implicit. Everywhere else in this function every value carries a concrete Numba type, same as mul_numba in the previous notebook. The objmode block is different: it’s compiled as a call to a synthetic ObjModeLiftedWith — Numba’s internal machinery for “a chunk of ordinary Python, called from compiled code” — and its inputs and outputs are typed as ffi_forced_object, not a real Numba type at all:
kepler_numba.inspect_types()kepler_objmode (Array(float64, 1, 'C', False, aligned=True), float64)
--------------------------------------------------------------------------------
# File: /tmp/ipykernel_550604/3384821370.py
# --- LINE 1 ---
# label 0
# M = arg(0, name=M) :: array(float64, 1d, C)
# e = arg(1, name=e) :: float64
def kepler_objmode(M, e):
# --- LINE 2 ---
# $4load_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'>)
# $14load_attr.1 = getattr(value=$4load_global.0, attr=empty_like) :: Function(<built-in function empty_like>)
# del $4load_global.0
# E = call $14load_attr.1(M, func=$14load_attr.1, args=[Var(M, 3384821370.py:1)], kws=(), vararg=None, varkwarg=None, target=None) :: (Array(float64, 1, 'C', False, aligned=True), omitted(default=None)) -> array(float64, 1d, C)
# del $14load_attr.1
E = np.empty_like(M)
# --- LINE 3 ---
# $46load_global.5 = global(range: <class 'range'>) :: Function(<class 'range'>)
# $58load_attr.8 = getattr(value=M, attr=shape) :: UniTuple(int64 x 1)
# $const78.9.0 = const(int, 0) :: Literal[int](0)
# $80binary_op.10 = static_getitem(value=$58load_attr.8, index=0, index_var=$const78.9.0, fn=<built-in function getitem>) :: int64
# del $const78.9.0
# del $58load_attr.8
# $92call.11 = call $46load_global.5($80binary_op.10, func=$46load_global.5, args=[Var($80binary_op.10, 3384821370.py:3)], kws=(), vararg=None, varkwarg=None, target=None) :: (int64,) -> range_state_int64
# del $80binary_op.10
# del $46load_global.5
# $100get_iter.12 = getiter(value=$92call.11) :: range_iter_int64
# del $92call.11
# $phi102.0 = $100get_iter.12 :: range_iter_int64
# del $100get_iter.12
# jump 102
# label 102
# $102for_iter.1 = iternext(value=$phi102.0) :: pair<int64, bool>
# $102for_iter.2 = pair_first(value=$102for_iter.1) :: int64
# $102for_iter.3 = pair_second(value=$102for_iter.1) :: bool
# del $102for_iter.1
# $phi106.1 = $102for_iter.2 :: int64
# del $102for_iter.2
# branch $102for_iter.3, 106, 282
# label 106
# del $102for_iter.3
# i = $phi106.1 :: int64
# del $phi106.1
# label 282
for i in range(M.shape[0]):
# --- LINE 4 ---
# Mi = getitem(value=M, index=i, fn=<built-in function getitem>) :: float64
Mi = M[i]
# --- LINE 5 ---
# $124load_global.5 = global(objmode: <numba.core.withcontexts._ObjModeContextType object at 0x146d97a08d70>) :: ContextManager(<numba.core.withcontexts._ObjModeContextType object at 0x146d97a08d70>)
# $const134.7.1 = const(str, float64) :: Literal[str](float64)
# $const_Ei = const(str, Ei) :: Literal[str](Ei)
# $const136.8.2 = build_tuple(items=[Var($const_Ei, 3384821370.py:5)]) :: UniTuple(Literal[str](Ei) x 1)
# del $const_Ei
# del $const136.8.2
# $138call_kw.9 = call $124load_global.5(func=$124load_global.5, args=[], kws=[('Ei', Var($const134.7.1, 3384821370.py:5))], vararg=None, varkwarg=None, target=None) :: (Literal[str](float64),) -> ContextManager(<numba.core.withcontexts._ObjModeContextType object at 0x146d97a08d70>)
# del $const134.7.1
# del $124load_global.5
# $phi166.2 = $138call_kw.9 :: ContextManager(<numba.core.withcontexts._ObjModeContextType object at 0x146d97a08d70>)
# del $phi166.2
# $phi148.2 = $138call_kw.9 :: ContextManager(<numba.core.withcontexts._ObjModeContextType object at 0x146d97a08d70>)
# del $phi148.2
# del $138call_kw.9
# jump 148
# label 148
# $59 = const(ObjModeLiftedWith, ObjModeLiftedWith(<function kepler_objmode at 0x146d94a4ca90>)) :: type(ObjModeLiftedWith(<function kepler_objmode at 0x146d94a4ca90>))
# $60 = call $59(Mi, e, func=$59, args=[Var(Mi, 3384821370.py:4), Var(e, 3384821370.py:1)], kws=(), vararg=None, varkwarg=None, target=None) :: (ffi_forced_object, ffi_forced_object) -> UniTuple(float64 x 1)
# del Mi
# del $59
# Ei = static_getitem(value=$60, index=0, index_var=None, fn=<built-in function getitem>) :: float64
# del $60
# jump 168
# $const254.18.5 = const(NoneType, None) :: none
# del $const254.18.5
# $const256.19.5 = const(NoneType, None) :: none
# del $const256.19.5
# $const258.20.5 = const(NoneType, None) :: none
# del $const258.20.5
with objmode(Ei="float64"):
# --- LINE 6 ---
# label 168
Ei = optimize.brentq(kepler_equation, Mi - 1.1, Mi + 1.1, args=(Mi, e))
# --- LINE 7 ---
# jump 270
# label 270
# E[i] = Ei :: (Array(float64, 1, 'C', False, aligned=True), int64, float64) -> none
# del i
# del Ei
# jump 102
E[i] = Ei
# --- LINE 8 ---
# del e
# del M
# del $phi106.1
# del $phi102.0
# del $102for_iter.3
# $288return_value.3 = cast(value=E) :: array(float64, 1d, C)
# del E
# return $288return_value.3
return E
# The function contains lifted loops
# Loop at line 6
# Has 1 overloads
# File: /tmp/ipykernel_550604/3384821370.py
# --- LINE 1 ---
def kepler_objmode(M, e):
# --- LINE 2 ---
E = np.empty_like(M)
# --- LINE 3 ---
for i in range(M.shape[0]):
# --- LINE 4 ---
Mi = M[i]
# --- LINE 5 ---
# pop_block
with objmode(Ei="float64"):
# --- LINE 6 ---
# label 148
# Mi = arg(0, name=Mi) :: <missing>
# e = arg(1, name=e) :: <missing>
# jump 166
# label 166
# $166load_global.3 = global(optimize: <module 'scipy.optimize' from '/home/kolen/.cache/Linux-x86_64/pixi/envs/jit_comparison-4669063116758098887/envs/default/lib/python3.14/site-packages/scipy/optimize/__init__.py'>) :: <missing>
# $176load_attr.4 = getattr(value=$166load_global.3, attr=brentq) :: <missing>
# del $166load_global.3
# $196load_global.6 = global(kepler_equation: <function kepler_equation at 0x146d957df690>) :: <missing>
# $const208.8.3 = const(float, 1.1) :: <missing>
# $binop_sub210.9 = Mi - $const208.8.3 :: <missing>
# del $const208.8.3
# $const224.11.3 = const(float, 1.1) :: <missing>
# $binop_add226.12 = Mi + $const224.11.3 :: <missing>
# del $const224.11.3
# $240build_tuple.15 = build_tuple(items=[Var(Mi, 3384821370.py:4), Var(e, 3384821370.py:1)]) :: <missing>
# del e
# del Mi
# $const_args = const(str, args) :: <missing>
# $const242.16.4 = build_tuple(items=[Var($const_args, 3384821370.py:6)]) :: <missing>
# del $const_args
# del $const242.16.4
# Ei = call $176load_attr.4($196load_global.6, $binop_sub210.9, $binop_add226.12, func=$176load_attr.4, args=[Var($196load_global.6, 3384821370.py:6), Var($binop_sub210.9, 3384821370.py:6), Var($binop_add226.12, 3384821370.py:6)], kws=[('args', Var($240build_tuple.15, 3384821370.py:6))], vararg=None, varkwarg=None, target=None) :: pyobject
# del $binop_sub210.9
# del $binop_add226.12
# del $240build_tuple.15
# del $196load_global.6
# del $176load_attr.4
# jump 167
# label 167
# jump 168
# label 168
# $58 = build_tuple(items=[Var(Ei, 3384821370.py:6)]) :: <missing>
# del Ei
# return $58
Ei = optimize.brentq(kepler_equation, Mi - 1.1, Mi + 1.1, args=(Mi, e))
# --- LINE 7 ---
E[i] = Ei
# --- LINE 8 ---
return E
================================================================================
The two lines to look for are the ObjModeLiftedWith call itself and the ffi_forced_object type it’s stamped with — that type is Numba’s way of writing “opaque PyObject*, ask CPython, not me”. Everything above and below that call — i, Mi, E[i] = Ei — is a normal typed Numba value, exactly like the rest of the function. The objmode block is a hole punched clean through the type system, not a smaller version of it.
Timing: the hole is exactly as slow as it looks
If objmode only lowers the loop scaffolding around one interpreted call, and that call is where almost all the time goes, compiling the scaffolding should barely matter. That’s testable, not just arguable — time all three versions on the same input:
for name, fn in [
("python", kepler_python),
("forceobj", kepler_forceobj),
("objmode", kepler_numba),
]:
seconds = min(timeit.repeat(lambda fn=fn: fn(M, e), number=3, repeat=5)) / 3
print(f"{name:>9}: {seconds * 1e3:.2f} ms") python: 12.63 ms
forceobj: 12.79 ms
objmode: 13.26 ms
All three land in the same range. forceobj buys nothing over plain Python, which the empty nopython_signatures list already predicted. objmode compiles the loop around the call — real lowering, confirmed above — and it still buys nothing measurable, because brentq’s handful of kepler_equation evaluations per element was always where the time went, not the for loop that calls it. Compiling the scaffold around a call that dominates the runtime doesn’t touch the runtime.
kepler_python and kepler_numba agree numerically, which is the property objmode actually guarantees — correctness of the escape hatch, not speed of what’s inside it:
np.allclose(kepler_python(M, e), kepler_numba(M, e))True
So what is objmode actually for?
Not performance — the timing above rules that out directly for this example. Its value is in what it lets you keep: nopython=True on the rest of a larger function. A function using objmode for one unsupported call is still checked, still typed, still fails loudly (with a real TypingError, at the usual pipeline stage) if a mistake is made anywhere outside the block — exactly like mul_numba in the first notebook. Reach for forceobj=True instead and every one of those guarantees is gone for the entire function, silently, whether or not the rest of it could have compiled. objmode is nopython’s way of saying “everything here is fully typed and lowered except this one named exception” — a guard around the parts of the function that are jitted for real, not a performance feature in its own right. Picture kepler_objmode’s loop body doing real per-step work of its own — propagating a state vector, say — around the one line that calls brentq: that surrounding work would be genuinely compiled, and only the irreducibly scalar root solve would keep paying the interpreter’s price. If the part inside the block turns out to dominate the runtime — as it does here, where the loop body is the brentq call — that’s a cost objmode reports honestly, not one it was ever claiming to remove.