Skip to content

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.

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.

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.4142135623730951
3.141592653589793
265252859812191058636308480000000

Let’s go through it:

  • from std.python import Python brings in Python, the door into the Python world.
  • Python.import_module("math") does what import math does 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 the 2 into a Python int for you, and the result comes back as a Python object you can print.
  • math.factorial(30) is a 33-digit number. A Mojo Int can’t hold that (it’s 64 bits), but the result stays a Python int, which has no size limit.

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 module

The 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 error
mojo: error: execution exited with a non-zero result: 1

That’s the same math domain error Python itself gives you for math.sqrt(-1).

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/python3

If 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.

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:

Terminal window
uv run mojo main.mojo
stack 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: 1

No module named 'numpy' is Python’s own message: that Python looked for the package and didn’t find it. Add it to the project:

Terminal window
uv add numpy
uv run mojo main.mojo

Output:

[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.

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:

Terminal window
mojo build main.mojo -o numbers
source .venv/bin/activate
./numbers

Output:

[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.

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.

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: 18
median: 15.5

Mojo 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_installed
No 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’s import name. Store the module in a variable and use it through that.
  • Every Python call can raise, so use def main() raises: or try/except.
  • Mojo uses the python3 on your PATH: activate the project’s .venv or use uv run so it’s the right one.
  • Install Python packages with uv add <package>. “No module named …” means that Python doesn’t have it.
  • mojo build doesn’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

1. What is the Mojo version of Python's import json?
2. You ran uv add numpy, but mojo main.mojo still says "No module named 'numpy'". What is the most likely reason?
3. Why does def main(): (without raises) fail to compile when it calls Python.import_module()?
4. You build a Mojo program that uses NumPy with mojo build. What does the executable need when it runs?