Mojo and Python
Mojo looks a lot like Python, but it isn’t Python: it’s a compiled language with its own types and its own standard library. The good news is that the two can work together. A Mojo program can import Python modules and call them, and a Python program can import code you wrote in Mojo. This page is the overview: how the two sides meet, which Python your Mojo program actually talks to, and how to install Python packages for it. The next pages go into each direction in detail.
Every example on this page was checked with Mojo 1.2 and Python 3.13 on Linux.
Two directions
Section titled “Two directions”There are two ways to mix the languages, and they solve different problems:
| Direction | What it’s for | How it works |
|---|---|---|
| Mojo calls Python | Use a Python library (NumPy, json, your own .py files) from a Mojo program |
Mojo loads the normal Python interpreter (CPython) and calls into it |
| Python calls Mojo | Speed up one slow part of a Python project by writing it in Mojo | You write a small Mojo module, and Python imports it like any other module |
Because Mojo calls the real CPython interpreter, Python libraries behave exactly as they do in Python. Nothing is rewritten or translated. The Mojo manual’s Python interoperability page has a diagram of both directions.
Your first Python call
Section titled “Your first Python call”Here’s a Mojo program that uses Python’s math module:
from std.python import Python
def main() raises: var math = Python.import_module("math") print(math.sqrt(2)) print(math.pi) print(math.factorial(30))Output:
1.41421356237309513.141592653589793265252859812191058636308480000000Let’s go through it:
from std.python import Pythonbrings inPython, the door into the Python world.Python.import_module("math")does whatimport mathdoes in Python, and gives you the module back. You store it in a variable and use it through that variable.math.sqrt(2)calls a Python function. Mojo turns the2into a Pythonintfor you, and the result comes back as a Python object you can print.math.factorial(30)is a 33-digit number. A MojoIntcan’t hold that (it’s 64 bits), but the result stays a Pythonint, which has no size limit.
Why main needs raises
Section titled “Why main needs raises”Anything Python does can fail: the module might not exist, a function might throw an exception. So every Python call in Mojo can raise an error, and Mojo makes you deal with that. Leave out raises and the program doesn’t compile:
from std.python import Python
def main(): var math = Python.import_module("math") print(math.pi)hello.mojo:4:36: error: cannot call function that may raise in a context that cannot raise var math = Python.import_module("math") ~~~~~~~~~~~~~~~~~~~~^~~~~~~~hello.mojo:4:36: note: try surrounding the call in a 'try' block var math = Python.import_module("math") ^hello.mojo:3:5: note: or mark surrounding function as 'raises'def main(): ^mojo: error: failed to parse the provided Mojo source moduleThe notes give you both fixes: write def main() raises:, or wrap the Python calls in try/except. If you haven’t met those yet, Mojo Errors and Mojo Try and Except explain them.
When a Python call fails while the program runs, the Python exception becomes a Mojo error with the same message:
from std.python import Python
def main() raises: var math = Python.import_module("math") print(math.sqrt(-1))stack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: math domain errormojo: error: execution exited with a non-zero result: 1That’s the same math domain error Python itself gives you for math.sqrt(-1).
Which Python does Mojo use?
Section titled “Which Python does Mojo use?”Mojo doesn’t include its own Python. When your program first touches Python, Mojo looks for the python3 command on your PATH and loads that Python. So the Python you get depends on how you start the program:
| You run | Mojo uses |
|---|---|
mojo main.mojo after source .venv/bin/activate |
The Python in your project’s .venv |
uv run mojo main.mojo |
The Python in your project’s .venv |
mojo main.mojo with no environment active |
Whatever python3 your system finds first |
This matters because Python packages are installed into one particular Python. If you install NumPy into your project’s .venv but Mojo picks up the system Python, it won’t find NumPy.
You can ask Python itself which one you got:
from std.python import Python
def main() raises: var sys = Python.import_module("sys") print("Python", sys.version_info.major, sys.version_info.minor) print(sys.executable)You’ll see something like this (your version and folder will be different):
Python 3 13/home/you/hello-world/.venv/bin/python3If the path points into your project’s .venv, you’re set. Mojo needs Python 3.10 to 3.14 for this to work; the Calling Python from Mojo page in the manual mentions the version and recommends always running inside a project environment.
Installing a Python package
Section titled “Installing a Python package”Python packages go into your project with uv, the same tool that installed Mojo in Mojo Get Started. Say your program uses NumPy:
from std.python import Python
def main() raises: var np = Python.import_module("numpy") var a = np.array([1, 2, 3]) print(a * 10)In a fresh project that only has Mojo in it, NumPy isn’t installed yet, so the import fails when the program runs:
uv run mojo main.mojostack trace was not collected. Enable stack trace collection with environment variable `MODULAR_DEBUG=stack-trace-on-error`Unhandled exception caught during execution: No module named 'numpy'mojo: error: execution exited with a non-zero result: 1No module named 'numpy' is Python’s own message: that Python looked for the package and didn’t find it. Add it to the project:
uv add numpyuv run mojo main.mojoOutput:
[10 20 30]uv add numpy downloads NumPy into the project’s .venv and writes it into pyproject.toml, next to mojo, so anyone who sets up the project later gets it too. The uv guide to managing dependencies has the details.
Built programs need Python too
Section titled “Built programs need Python too”mojo build turns your program into an executable, but it doesn’t copy Python or your Python packages into it. The executable loads Python when it runs, using the same python3 lookup as above. So run it where the packages are installed, for example with the environment active:
mojo build main.mojo -o numberssource .venv/bin/activate./numbersOutput:
[10 20 30]This is different from a Python tool like PyInstaller that bundles everything. If you give the executable to someone else, they need Mojo’s runtime, a supported Python and the same packages.
What about speed?
Section titled “What about speed?”Calling Python from Mojo runs that Python code at Python speed. Mojo can’t make NumPy or json faster; it just calls them. The speed comes from the parts you write in Mojo itself. A common pattern is to use Python libraries for the jobs they’re good at (loading data, plotting, talking to web services) and write the number-crunching loops in Mojo.
The other direction works the same way: a Python program that imports a Mojo module gets Mojo speed only inside that module. Mojo Calling Mojo from Python shows it, with a timing we measured.
Practice
Section titled “Practice”1. Mean and median
Section titled “1. Mean and median”Python has a statistics module. Use it from Mojo to print the mean and the median of the numbers 4, 8, 15, 16, 23 and 42.
Hint: pass a list straight into the function: statistics.mean([4, 8, 15, 16, 23, 42]).
Show solution
from std.python import Python
def main() raises: var statistics = Python.import_module("statistics") print("mean:", statistics.mean([4, 8, 15, 16, 23, 42])) print("median:", statistics.median([4, 8, 15, 16, 23, 42]))Output:
mean: 18median: 15.5Mojo turns the list literal into a Python list, and statistics does the rest. The mean is a whole number here, so Python gives back an int; the median sits between 15 and 16, so it’s a float.
2. A friendly message for a missing package
Section titled “2. A friendly message for a missing package”Write a program that tries to import a package called pandas_not_installed. Instead of crashing, it should print Please install it with: uv add pandas_not_installed followed by Python’s error message on the next line.
Hint: drop raises from main and put the import inside try:. The error you catch with except e: prints as Python’s message.
Show solution
from std.python import Python
def main(): try: var pd = Python.import_module("pandas_not_installed") print(pd) except e: print("Please install it with: uv add pandas_not_installed") print(e)Output:
Please install it with: uv add pandas_not_installedNo module named 'pandas_not_installed'Because the failing call is inside try, main doesn’t need raises. The except block runs instead of the program stopping, and e holds the message Python produced.
- Mojo and Python work together in both directions: Mojo can import Python modules, and Python can import Mojo modules.
Python.import_module("name")is Mojo’simport name. Store the module in a variable and use it through that.- Every Python call can raise, so use
def main() raises:ortry/except. - Mojo uses the
python3on yourPATH: activate the project’s.venvor useuv runso it’s the right one. - Install Python packages with
uv add <package>. “No module named …” means that Python doesn’t have it. mojo builddoesn’t bundle Python packages, and Python code still runs at Python speed.
Next up: Mojo Calling Python, importing modules, calling functions and methods, and using your own .py files.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Python interoperability: the manual’s overview of both directions, with a diagram.
- Calling Python from Mojo: importing modules, local Python files and choosing a Python version.
- Python struct reference: every method on
Python, such asimport_module,add_to_pathandevaluate. - Managing dependencies with uv: how
uv addandpyproject.tomlwork. - Mojo tips for Python devs: where Python habits carry over to Mojo and where they don’t.