For the complete Mojo documentation index, see llms.txt. Markdown versions of all pages are available by appending .md to any URL (e.g. /docs/manual/basics.md).
Calling Mojo from Python
Calling Mojo from Python unlocks two key ways to improve an existing application. First, you can speed up performance-critical code by moving your hot loops into Mojo while keeping the rest of your application in Python. Second, you can migrate your codebase to Mojo incrementally, one module at a time, without committing to a complete rewrite.
Both Mojo and Python have real strengths. Mojo shines at computation-heavy code that performs many operations on its values. Python remains a familiar environment for application logic, libraries, and code that doesn't need optimization. Combining them lets you use each language where it provides the most value.
When you start with performance-critical code, Mojo interop can eliminate much of Python's runtime overhead. Yes, calls between the two languages have a cost, but moving an entire hot loop into Mojo can yield measurable performance gains. Try to move the entire routine to Mojo. It's more effective than calling Mojo repeatedly from inside a Python loop.
This page demonstrates:
- Moving a hot loop from Python into Mojo and calling it from an existing Python program.
- Exposing native Mojo structs and their methods as Python types.
- Building, importing, and distributing Mojo modules for use in Python.
Start by moving a prime-counting function into Mojo and comparing its performance with Python. Then, expose a Mojo statistics type that Python can create and use like a regular class.
Move a hot loop into Mojo
Mojo offers the greatest performance benefits when your code:
- Performs many small operations, such as loop iteration, recursion, tree walks, parsing, or simulations.
- Frequently reads and updates fields in native Mojo types.
- Can benefit from SIMD or parallel execution. Mojo can vectorize loops and run them in parallel.
Calls between Python and Mojo have a small but measurable cost. For the best results, move substantial units of work. Avoid making many small calls across the language boundary.
Counting primes
The following Python function counts the primes below some limit you specify. It tests each odd number against odd divisors, using two nested loops:
def count_primes(limit):
# Count 2 separately because the loop skips even numbers.
count = 1 if limit > 2 else 0
for n in range(3, limit, 2):
is_prime = True
for d in range(3, n, 2):
if d * d > n:
break
if n % d == 0:
is_prime = False
break
if is_prime:
count += 1
return count
This Mojo version keeps the same loops and logic. Apart from the type
annotations and var to declare variables, it matches the Python line for
line:
def count_primes(limit: Int) -> Int:
# Count 2 separately because the loop skips even numbers.
var count = 1 if limit > 2 else 0
for n in range(3, limit, 2):
var is_prime = True
for d in range(3, n, 2):
if d * d > n:
break
if n % d == 0:
is_prime = False
break
if is_prime:
count += 1
return count
This is ordinary Mojo. Other Mojo code can call it, and you can test it without Python.
Calling Mojo from Python
To call the Mojo function from Python, add a Python-facing wrapper and a
module entry point to fast_primes.mojo:
# Add to the top of the Mojo file
from std.os import abort
from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder
# Python-facing wrapper to call `count_primes()`
def py_count_primes(limit: PythonObject) raises -> PythonObject:
return count_primes(Int(py=limit))
# Python-facing module
@export
def PyInit_fast_primes() abi("C") -> PythonObject:
try:
var module = PythonModuleBuilder("fast_primes")
module.def_function[py_count_primes]("count_primes")
return module.finalize()
except e:
abort(t"error creating fast_primes: {e}")
The py_count_primes() wrapper handles conversion between Python and
Mojo. Python passes the argument as a
PythonObject.
The wrapper converts
it to a Mojo Int, calls the native count_primes() function, and
returns the result as a PythonObject.
As in this example, keep PythonObject operations at the module boundary. Each
operation
goes through the Python interpreter.
The overhead of repeated conversions can make Mojo code slower than the Python
code it replaces. Convert values at the module boundary and perform your
computations on native Mojo values.
PythonModuleBuilder
defines the module's Python-facing API. Create it with the module name,
register functions with
def_function(),
and then call
finalize()
to create the module. Here, the builder registers py_count_primes()
as count_primes(), the function Python code can call.
PyInit_fast_primes() is the initialization function for the compiled
Python extension
module. When Python
imports fast_primes, it calls this function. Native CPython extension
modules written in Mojo, C, C++, or Rust all expose PyInit_<modulename>
as a C-ABI symbol.
Since Python calls the entry point through the
C ABI, it requires
the @export decorator and
the abi("C") effect.
Because an abi("C") function can't raise, the entry point catches
errors and calls abort() instead.
Registered functions such as py_count_primes() don't need these
annotations. The builder wraps them and converts raised Mojo errors into
Python exceptions. It accepts plain functions, but not
closures. Closures can't serve
directly as plain C-compatible function pointers.
Run both versions
-
Create a project with Pixi and add Mojo and Python to it:
pixi init primes -c https://conda.modular.com/max-nightly -c conda-forgecd primespixi add mojo pythonThe
mojopackage includes the Mojo compiler andmojo.importer, the Python package that lets Python import.mojofiles. -
Save
primes.pyandfast_primes.mojoin the project directory. Put both Mojo blocks infast_primes.mojo. -
Add a script that imports both versions and times each one:
main.pyimport timeimport mojo.importerimport fast_primesimport primesfor module in (primes, fast_primes):start = time.perf_counter()count = module.count_primes(2_000_000)elapsed = time.perf_counter() - startprint(f"{module.__name__}: {count} primes in {elapsed:.2f} s")import mojo.importercomes first. After it runs,import fast_primesfindsfast_primes.mojo, compiles it, and loads the result. You don't run a separate compile step.The project now holds three code files (.mojo and .py):
primes├── fast_primes.mojo├── main.py├── pixi.toml└── primes.py -
Run the script:
pixi run python main.pyThe first line reports pure Python. The second reports the same Python program with its hot loop offloaded to Mojo. Both count 148,933 primes, and the Mojo version finishes in a fraction of the time.
The output will vary by machine and system load. Here's an example recorded on a 2024 MacBook Pro running macOS Tahoe:
$ pixi run python main.py
primes: 148933 primes in 2.91 s
fast_primes: 148933 primes in 0.06 s
That's the win. You rewrote one function, and the rest of the program stayed in Python.
The first run compiles fast_primes.mojo. Later runs reuse the compiled
module until you change the source. To compile the module yourself instead,
see Build and ship.
Give Mojo the whole loop
Pass Mojo the largest practical unit of work per call. Although calling
a Mojo function from Python takes little time, repeated
calls add overhead. For example, calling a Mojo is_prime() function
for each number in a Python loop loses some of the performance benefit.
Moving the entire loop into Mojo avoids those repeated calls.
How mojo.importer works
import mojo.importer installs a Python
import hook.
When Python imports a module it can't find as Python, the hook looks for a
matching .mojo file on
sys.path, compiles it
into an extension module, and loads it.
By default, the hook caches compiled modules in a __mojocache__
directory next to the source:
primes
├── __mojocache__
│ └── fast_primes.hash-ABC123.so
├── fast_primes.mojo
├── main.py
├── pixi.toml
└── primes.py
The hook recompiles a module when its source changes. You can delete
__mojocache__ at any time. The hook rebuilds what it needs on the next
import.
If the Mojo source doesn't compile, the import statement raises
ImportError, and the compiler's messages appear in the traceback.
Bridge Python to your Mojo types
As a migration goes on, more of your program moves into Mojo. Hot functions lead the way, and the types that hold your data follow. The Python code that remains still creates those objects, calls their methods, and passes them around, so each Mojo type needs a bridge that Python can use.
This direction differs from converting Python objects to Mojo, where Mojo code copies a Python value into a Mojo struct. Here, the Mojo struct is the definition. Python gets a type whose objects hold Mojo values, and each method call runs Mojo code on them.
Capturing running stats
This Mojo struct keeps running statistics for a stream of measurements, such as request latencies. It stores a count, a mean, and a running sum of squared deviations from the mean. It only keeps track of squared differences, so it never holds the samples themselves, and two partial results can merge into one:
from std.math import sqrt
struct RunningStats(Defaultable, Movable, Writable):
var count: Int
var mean: Float64
var m2: Float64
def __init__(out self):
self.count = 0
self.mean = 0.0
self.m2 = 0.0
def add(mut self, value: Float64):
self.count += 1
var delta = value - self.mean
self.mean += delta / Float64(self.count)
self.m2 += delta * (value - self.mean)
def merge(mut self, other: Self):
if other.count == 0:
return
var total = self.count + other.count
var delta = other.mean - self.mean
var weight = (
Float64(self.count) * Float64(other.count) / Float64(total)
)
self.mean += delta * Float64(other.count) / Float64(total)
self.m2 += other.m2 + delta * delta * weight
self.count = total
def stddev(self) -> Float64:
if self.count < 2:
return 0.0
return sqrt(self.m2 / Float64(self.count - 1))
As with count_primes(), nothing here knows about Python. The interface
goes in the same file, as functions outside the struct:
from std.os import abort
from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder
def py_add(py_self: PythonObject, args: PythonObject) raises -> PythonObject:
var stats = py_self.downcast_value_ptr[RunningStats]()
for value in args:
stats[].add(Float64(py=value))
return None
def py_merge(
self: Pointer[RunningStats, MutUnsafeAnyOrigin], other: PythonObject
) raises:
self[].merge(other.downcast_value_ptr[RunningStats]()[])
def py_mean(
self: Pointer[RunningStats, MutUnsafeAnyOrigin]
) raises -> PythonObject:
return self[].mean
def py_stddev(
self: Pointer[RunningStats, MutUnsafeAnyOrigin]
) raises -> PythonObject:
return self[].stddev()
def py_from_values(values: PythonObject) raises -> PythonObject:
var stats = RunningStats()
for value in values:
stats.add(Float64(py=value))
return PythonObject(alloc=stats^)
@export
def PyInit_fast_stats() abi("C") -> PythonObject:
try:
var module = PythonModuleBuilder("fast_stats")
_ = (
module.add_type[RunningStats]("RunningStats")
.def_init_defaultable[RunningStats]()
.def_py_method[py_add](
"add", docstring="Add one or more samples."
)
.def_method[py_merge]("merge")
.def_method[py_mean]("mean")
.def_method[py_stddev]("stddev")
.def_staticmethod[py_from_values](
"from_values", docstring="Build stats from an iterable."
)
)
return module.finalize()
except e:
abort(t"error creating fast_stats: {e}")
add_type() registers the struct as a Python type named RunningStats
and returns a
PythonTypeBuilder.
Each chained call adds one thing Python can do with the type:
- Create objects. Python can't call a Mojo
__init__()directly.def_init_defaultable()lets Python callRunningStats()with no arguments. For an initializer that takes arguments, usedef_py_init(). - Call methods.
def_method()registers an instance method. Its function receives the object as aPointerto the Mojo value, sopy_mean()reads the struct's fields throughself[]. - Pass any number of arguments.
def_py_method()passes the object and a tuple holding every positional argument, soadd()accepts one sample or many. Its function receives the object as aPythonObjectand gets the Mojo value withdowncast_value_ptr(). - Accept objects back.
merge()receives anotherRunningStatsas aPythonObjectand downcasts it the same way. The downcast checks the type, so passing a list raises an error that names the expected type. Mojo doesn't track aliasing through a downcast pointer, so see Interop safety before you mutate through two of them. - Return new objects.
def_staticmethod()registers a method that Python calls on the type itself.from_values()builds a struct in Mojo, andPythonObject(alloc=)wraps it in a new Python object of the registered type.
Python uses the type like any other class:
import mojo.importer
from fast_stats import RunningStats
latency = RunningStats()
latency.add(12.5, 9.8, 14.1)
latency.add(11.0)
batch = RunningStats.from_values([30.2, 10.7])
latency.merge(batch)
print(f"mean {latency.mean():.2f} ms, stddev {latency.stddev():.2f} ms")
print(latency)
The script reports the mean and sample standard deviation of all six
samples, then prints the object itself. Python prints a Mojo object through
the struct's Writable conformance, which
add_type() requires. Each Mojo type maps to one Python type, so
registering the same struct a second time raises an error.
For every registration method, see
PythonModuleBuilder
and PythonTypeBuilder.
Sharp edges
- Arguments arrive in Mojo as
PythonObjectvalues. Convert each one to Mojo using apy=initializer before your loop starts when possible. A failed conversion raises a Python exception. For conversion rules and your own types, see Converting between Mojo and Python types. - Python sees methods, not fields. The struct's fields aren't Python
attributes, and the bindings don't support properties. Python can't add
attributes of its own either, because the object has no
__dict__. To read or change state, register a method that does it. - Interface functions inside a struct need
@staticmethod. If you declarepy_mean()and the others as struct members instead of free functions, mark each one@staticmethod. Without it, the module doesn't compile, and theimportraisesImportError. - Keyword arguments arrive through
var **kwargs: PythonObject. Look them up by name:Int(py=kwargs["scale"]). Mojo keyword-only parameters (*, scale: PythonObject) and variadic parameters (*args: PythonObject) don't bind withdef_function(). To accept a variable number of arguments, register a function withdef_py_function()or a method withdef_py_method(), asadd()does. Each receives the arguments as one Python tuple. - Errors lose their Python type. A call with the wrong number of arguments
raises a plain
Exceptionwhose message starts withTypeError:, soexcept TypeErrordoesn't catch it. Initializers are the exception: any error fromdef_init_defaultable()ordef_py_init()reaches Python as aValueError, whatever caused it. To raise a specific Python exception type, useraise_python_exception(). See Interop safety.
Build and ship
During development, mojo.importer compiles each module on import, so
your edits take effect the next time Python runs.
The importer runs mojo build without extra
options. To set build options, such as import paths for Mojo packages or
optimization flags, build the extension module yourself:
mojo build fast_primes.mojo --emit shared-lib -o fast_primes.so
The --emit shared-lib option is one of several
emit options. Python
imports fast_primes.so like any other extension module, without
mojo.importer. Ship the .so file with your Python package.
For Python version support and the runtime libraries a prebuilt module needs, see Interop safety.
Worth knowing
- Compare the same algorithm. When you time Mojo against Python, make both versions run the same algorithm. A better algorithm speeds up either language, and mixing the two hides what Mojo contributes.
- Python holds the GIL for GIL-enabled Python builds while your Mojo function runs. Other Python threads that need the GIL wait until the call returns.
- NumPy arrays don't need copying. To run a hot loop over a NumPy array, borrow its memory instead of converting it element by element. Each borrow has a small fixed cost, so pass large arrays. See Share memory with NumPy.
- Compile-time choices happen at build time.
Parameters and
comptimevalues are fixed when the module compiles, and Python passes only runtime values. To offer several specializations, register each one, or pick one in the wrapper based on the arguments. - A missing keyword argument doesn't name the key. Looking up an
absent key in
kwargsraises anExceptionwhose message namesDictKeyErrorbut not the key. To report the key, check for it first, for exampleif "scale" not in kwargs, and raise your own error. - The importer rebuilds by directory. It hashes every
.mojofile in the source's directory and its subdirectories, so editing any one of them invalidates cached modules, which rebuild on subsequent imports.