Skip to content

Mojo Calling Mojo from Python

So far, Mojo has been the one in charge, calling into Python. This page turns it around: you have a Python program, one part of it is too slow, and you’d like to write just that part in Mojo. Python then imports your Mojo code like any other module. You don’t rewrite the whole project, only the part that needs the speed.

You need two files in one folder:

project/
├── main.py
└── mojo_module.mojo

The Mojo file holds a function for Python to call, plus a bit of setup code that tells Python the function exists. This is the example from the manual’s Calling Mojo from Python page:

from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder
from std import math
from std.os import abort
@export
def PyInit_mojo_module() abi("C") -> PythonObject:
try:
var m = PythonModuleBuilder("mojo_module")
m.def_function[factorial]("factorial", docstring="Compute n!")
return m.finalize()
except e:
abort(String("error creating Python Mojo module:", e))
def factorial(py_obj: PythonObject) raises -> PythonObject:
# Raises an exception if `py_obj` is not convertible to a Mojo `Int`.
var n = Int(py=py_obj)
return math.factorial(n)

And the Python side, main.py:

import mojo.importer
import mojo_module
print(mojo_module.factorial(5))

Run it with the Python from your project (the one where you did uv add mojo):

Terminal window
uv run python main.py

Output:

120

The first run takes a few seconds (about five on our machine), because Mojo compiles mojo_module.mojo first. After that it starts right away.

There’s a lot of new stuff in that Mojo file, so let’s take it line by line.

def factorial(py_obj: PythonObject) raises -> PythonObject is the function Python calls. Whatever Python passes in arrives as a PythonObject, and whatever you return goes back as one. Inside, you convert to real Mojo types: Int(py=py_obj) turns the Python number into a Mojo Int. The return turns the Mojo Int back into a Python int for you.

PyInit_mojo_module() is what Python looks for when it imports a compiled module called mojo_module. The name must be PyInit_ plus the file name. (For fast_math.mojo it’s PyInit_fast_math.) Inside it:

  • PythonModuleBuilder("mojo_module") starts building a Python module.
  • m.def_function[factorial]("factorial", docstring="Compute n!") adds your Mojo function under the name factorial, with a docstring for Python’s help().
  • m.finalize() finishes the module and hands it to Python.

@export makes the function visible outside the compiled file, and abi("C") says it uses C’s calling convention, which is how Python calls it. A function with abi("C") isn’t allowed to raise, so any error is caught and passed to abort(), which stops the program with that message. Your own functions, like factorial, don’t need any of this: they can raise freely, and Mojo turns their errors into Python exceptions.

import mojo.importer on the Python side is what makes the magic happen. It teaches Python’s import to look for .mojo files. When it finds mojo_module.mojo, it compiles it into a library and puts that in a new folder:

project/
├── __mojocache__
│ └── mojo_module.hash-7e787e01be377c4d.so
├── main.py
└── mojo_module.mojo

Change the .mojo file and the next import rebuilds it. The __mojocache__ folder only holds build results, so it’s always safe to delete. To Python, the .so file is a normal extension module, the same kind of compiled module NumPy is made of.

import mojo.importer comes from the mojo Python package, which uv add mojo installed into your project. Run the script with a Python that doesn’t have it, like the system one, and the very first line fails:

Terminal window
python3 main.py
Traceback (most recent call last):
File "/home/you/project/main.py", line 1, in <module>
import mojo.importer
ModuleNotFoundError: No module named 'mojo'

Use uv run python main.py, or activate the environment first (source .venv/bin/activate) and then run python main.py.

Errors raised in your Mojo function arrive in Python as exceptions you can catch. Here’s errors.py, using the same module:

import mojo.importer
import mojo_module
print(mojo_module.factorial.__doc__)
try:
mojo_module.factorial("five")
except Exception as e:
print(type(e).__name__, "-", e)
try:
mojo_module.factorial(1, 2)
except Exception as e:
print(type(e).__name__, "-", e)

Output:

Compute n!
Exception - invalid literal for int() with base 10: 'five'
Exception - TypeError: <mojo function>() takes 1 positional argument but 2 were given

The docstring shows up where Python expects it. Notice that both errors arrive as a plain Exception, not as ValueError or TypeError; the original type only appears inside the message. So in Python, catch Exception around calls into Mojo.

If the Mojo file doesn’t compile, the import itself fails. For example, writing Int(py_obj) instead of Int(py=py_obj) gives a long report that ends like this (shortened):

mojo_module.mojo:17:16: error: no matching function in initialization
var n = Int(py_obj)
~~~^~~~~~~~
mojo: error: failed to parse the provided Mojo source module
...
ImportError: Import of Mojo module failed due to compilation error.

Look for the error: line with your file name in it; that’s the real problem. The rest is Python explaining that the import failed.

Factorial is a toy. Here’s something that’s actually slow in Python: counting prime numbers by trial division. Save this as fast_math.mojo:

from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder
from std.os import abort
@export
def PyInit_fast_math() abi("C") -> PythonObject:
try:
var m = PythonModuleBuilder("fast_math")
m.def_function[count_primes]("count_primes", docstring="Count the primes below n.")
return m.finalize()
except e:
abort(String("error creating the fast_math module:", e))
def count_primes(py_n: PythonObject) raises -> PythonObject:
var n = Int(py=py_n)
var count = 0
for candidate in range(2, n):
var is_prime = True
var d = 2
while d * d <= candidate:
if candidate % d == 0:
is_prime = False
break
d += 1
if is_prime:
count += 1
return count

Then compare it with the same code in Python, in main.py:

import time
import mojo.importer
import fast_math
def count_primes(n):
count = 0
for candidate in range(2, n):
is_prime = True
d = 2
while d * d <= candidate:
if candidate % d == 0:
is_prime = False
break
d += 1
if is_prime:
count += 1
return count
start = time.perf_counter()
print("Python:", count_primes(200_000), f"in {time.perf_counter() - start:.2f} s")
start = time.perf_counter()
print("Mojo: ", fast_math.count_primes(200_000), f"in {time.perf_counter() - start:.2f} s")

What we got on a Linux machine with a 2.1 GHz Intel Xeon (your times will differ):

Python: 17984 in 0.40 s
Mojo: 17984 in 0.01 s

Over three runs, Python took 0.39 to 0.41 seconds and Mojo 0.01 to 0.02 seconds. The code is line for line the same algorithm; the difference is that Mojo compiles the loop with real machine integers, while Python handles every number as an object. Notice what made this work well: Python calls Mojo once, and all the looping happens inside Mojo. If Python called a Mojo function a million times in a loop, the cost of crossing between the languages would eat much of the gain.

You can also give Python a Mojo type to use as a class. Here’s a small counter, in counter.mojo:

from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder
from std.os import abort
@export
def PyInit_counter() abi("C") -> PythonObject:
try:
var m = PythonModuleBuilder("counter")
_ = (
m.add_type[Counter]("Counter")
.def_init_defaultable[Counter]()
.def_method[Counter.add]("add")
.def_method[Counter.total]("total")
)
return m.finalize()
except e:
abort(String("error creating the counter module:", e))
struct Counter(Defaultable, Movable, Writable):
var count: Int
def __init__(out self):
self.count = 0
@staticmethod
def add(self_ptr: Pointer[Self, MutAnyOrigin], amount: PythonObject) raises:
self_ptr[].count += Int(py=amount)
@staticmethod
def total(self_ptr: Pointer[Self, MutAnyOrigin]) -> PythonObject:
return self_ptr[].count

And the Python side:

import mojo.importer
from counter import Counter
c = Counter()
c.add(5)
c.add(10)
print(c.total())
print(c)

Output:

15
Counter(count=Int(15))

What’s going on:

  • add_type[Counter]("Counter") makes Counter available as a Python class. The struct must be Writable (that’s what gives print(c) its text) and Movable.
  • def_init_defaultable[Counter]() lets Python write Counter(), using the struct’s __init__ with no arguments. That’s why the struct is also Defaultable.
  • def_method adds methods. For now they must be @staticmethods that take a pointer to the struct as their first argument, instead of a normal self. self_ptr[] gets you to the struct itself. The manual says this rule will go away in a later version.

For a constructor that takes arguments, like Person("Sarah", 32), there’s def_py_init. It’s shown on the PythonTypeBuilder reference and in the manual; remember to use Int(py=...) in it.

The import hook is the easy way to start. You can also build the library ahead of time with mojo build:

Terminal window
mojo build mojo_module.mojo --emit shared-lib -o mojo_module.so

Now main.py doesn’t need import mojo.importer any more; a plain import mojo_module finds the .so file:

import mojo_module
print(mojo_module.factorial(10))

Output:

3628800

This gives you control over build options, like optimization or debug flags. Keep in mind that the .so file still loads Mojo’s runtime libraries from the project’s .venv, the same as an executable from mojo build does.

The manual’s list of known limits is worth a read. The ones you’ll hit first: def_function takes fixed arguments only (no *args, and keyword arguments only through a special kwargs parameter), there are no properties (Python can’t read c.count, so you write a method like total()), and methods need the static-method form shown above.

Add a function square to mojo_module.mojo that takes a number and returns its square, and call it from Python: print(mojo_module.square(12)) should print 144.

Hint: write the function like factorial, then register it with one more m.def_function[...] line in PyInit_mojo_module.

Show solution
from std.python import PythonObject
from std.python.bindings import PythonModuleBuilder
from std import math
from std.os import abort
@export
def PyInit_mojo_module() abi("C") -> PythonObject:
try:
var m = PythonModuleBuilder("mojo_module")
m.def_function[factorial]("factorial", docstring="Compute n!")
m.def_function[square]("square", docstring="Compute n * n")
return m.finalize()
except e:
abort(String("error creating Python Mojo module:", e))
def factorial(py_obj: PythonObject) raises -> PythonObject:
var n = Int(py=py_obj)
return math.factorial(n)
def square(py_obj: PythonObject) raises -> PythonObject:
var n = Int(py=py_obj)
return n * n
import mojo.importer
import mojo_module
print(mojo_module.square(12))

Output:

144

Every function Python can see needs its own def_function line. Because you changed the .mojo file, the import hook rebuilds the module the next time you run main.py.

Give the Counter struct a reset method that sets the count back to 0. From Python, add 7, reset, add 2, and print the total, which should be 2.

Hint: copy the shape of add, but with only the self_ptr argument, and register it with another .def_method.

Show solution

Add this method to the struct:

@staticmethod
def reset(self_ptr: Pointer[Self, MutAnyOrigin]):
self_ptr[].count = 0

register it next to the others:

.def_method[Counter.reset]("reset")

and use it from Python:

import mojo.importer
from counter import Counter
c = Counter()
c.add(7)
c.reset()
c.add(2)
print(c.total())

Output:

2

self_ptr[] is the struct Python holds, so setting count through it changes that object. A method that returns nothing gives Python None, just like a Python method without return.

  • Python can import a Mojo file as an extension module: write the functions, then register them in PyInit_<module name> with PythonModuleBuilder.
  • PyInit_... needs @export and abi("C"), and can’t raise, so errors go to abort().
  • On the Python side, import mojo.importer compiles .mojo files on import and caches them in __mojocache__.
  • Run Python from the project environment (uv run python main.py), where the mojo package is installed.
  • Convert arguments with Int(py=...); Mojo errors reach Python as a plain Exception.
  • Speed comes from doing a lot of work per call inside Mojo. The feature is beta: expect changes.

Next up: Mojo Python Types, how values change as they move between Mojo and Python.

Quick check

1. Your Mojo file is called geometry.mojo. What must the setup function be called?
2. What does import mojo.importer do in a Python program?
3. A Mojo function bound with def_function raises an error. What does the Python caller get?
4. When does moving code from Python to Mojo help the most?