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.
The smallest example
Section titled “The smallest example”You need two files in one folder:
project/├── main.py└── mojo_module.mojoThe 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 PythonObjectfrom std.python.bindings import PythonModuleBuilderfrom std import mathfrom std.os import abort
@exportdef 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.importerimport mojo_module
print(mojo_module.factorial(5))Run it with the Python from your project (the one where you did uv add mojo):
uv run python main.pyOutput:
120The first run takes a few seconds (about five on our machine), because Mojo compiles mojo_module.mojo first. After that it starts right away.
How it works
Section titled “How it works”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 namefactorial, with a docstring for Python’shelp().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.mojoChange 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.
Use the right Python
Section titled “Use the right Python”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:
python3 main.pyTraceback (most recent call last): File "/home/you/project/main.py", line 1, in <module> import mojo.importerModuleNotFoundError: 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.
When things go wrong
Section titled “When things go wrong”Errors raised in your Mojo function arrive in Python as exceptions you can catch. Here’s errors.py, using the same module:
import mojo.importerimport 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 givenThe 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.
A function worth speeding up
Section titled “A function worth speeding up”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 PythonObjectfrom std.python.bindings import PythonModuleBuilderfrom std.os import abort
@exportdef 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 countThen compare it with the same code in Python, in main.py:
import time
import mojo.importerimport 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 sMojo: 17984 in 0.01 sOver 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.
Binding a struct
Section titled “Binding a struct”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 PythonObjectfrom std.python.bindings import PythonModuleBuilderfrom std.os import abort
@exportdef 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[].countAnd the Python side:
import mojo.importerfrom counter import Counter
c = Counter()c.add(5)c.add(10)print(c.total())print(c)Output:
15Counter(count=Int(15))What’s going on:
add_type[Counter]("Counter")makesCounteravailable as a Python class. The struct must beWritable(that’s what givesprint(c)its text) andMovable.def_init_defaultable[Counter]()lets Python writeCounter(), using the struct’s__init__with no arguments. That’s why the struct is alsoDefaultable.def_methodadds methods. For now they must be@staticmethods that take a pointer to the struct as their first argument, instead of a normalself.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.
Building the module yourself
Section titled “Building the module yourself”The import hook is the easy way to start. You can also build the library ahead of time with mojo build:
mojo build mojo_module.mojo --emit shared-lib -o mojo_module.soNow 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:
3628800This 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.
What doesn’t work yet
Section titled “What doesn’t work yet”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.
Practice
Section titled “Practice”1. Add a second function
Section titled “1. Add a second function”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 PythonObjectfrom std.python.bindings import PythonModuleBuilderfrom std import mathfrom std.os import abort
@exportdef 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 * nimport mojo.importerimport mojo_module
print(mojo_module.square(12))Output:
144Every 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.
2. A reset button
Section titled “2. A reset button”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 = 0register it next to the others:
.def_method[Counter.reset]("reset")and use it from Python:
import mojo.importerfrom counter import Counter
c = Counter()c.add(7)c.reset()c.add(2)print(c.total())Output:
2self_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>withPythonModuleBuilder. PyInit_...needs@exportandabi("C"), and can’t raise, so errors go toabort().- On the Python side,
import mojo.importercompiles.mojofiles on import and caches them in__mojocache__. - Run Python from the project environment (
uv run python main.py), where themojopackage is installed. - Convert arguments with
Int(py=...); Mojo errors reach Python as a plainException. - 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Calling Mojo from Python: the manual’s full guide, including keyword arguments, static methods and known limits.
- PythonModuleBuilder reference:
def_function,add_typeand the other ways to build a module. - PythonTypeBuilder reference: binding struct initializers and methods.
- The @export decorator: what
@exportandabi("C")mean. - Extending Python with C or C++: Python’s own docs on extension modules, if you want to know what happens underneath.