Skip to content

Mojo Calling Python

Mojo and Python showed that a Mojo program can use Python. This page is the practical part: importing modules from Python’s standard library, calling functions and methods (keyword arguments included), using a .py file you wrote yourself, running small bits of Python code, and dealing with Python exceptions. If you know Python, most of it will look familiar; the differences are in how you import and in error handling.

Every example on this page was checked with Mojo 1.2 and Python 3.13.

In Python you’d write import json. In Mojo you ask Python for the module and keep it in a variable:

from std.python import Python
def main() raises:
var json = Python.import_module("json")
var data = json.loads('{"name": "Ada", "langs": ["Python", "Mojo"]}')
print(data["name"])
print(data["langs"][1])
print(len(data["langs"]))

Output:

Ada
Mojo
2

json.loads turns the text into a Python dictionary, and from there it feels just like Python: data["name"] looks up a key, data["langs"][1] takes the second item of a list, and Mojo’s own len() works on Python objects too.

A few rules come with import_module, all listed on the manual’s Calling Python from Mojo page:

  • You import whole modules. There’s no Mojo version of from json import loads. Import json and write json.loads.
  • The import goes inside a function, because Mojo has no top-level code. Importing the same module again (say, in two functions) is cheap: Python only runs a module’s setup code once.
  • It can raise, so the function needs raises or a try block.

Python functions often take keyword arguments, like indent=2 or reverse=True. You pass them from Mojo exactly the same way:

from std.python import Python
def main() raises:
var json = Python.import_module("json")
var data = json.loads('{"name": "Ada", "year": 1843}')
print(json.dumps(data, indent=2))
var builtins = Python.import_module("builtins")
var words = Python.list("pear", "fig", "banana")
print(builtins.sorted(words))
print(builtins.sorted(words, key=builtins.len, reverse=True))

Output:

{
"name": "Ada",
"year": 1843
}
['banana', 'fig', 'pear']
['banana', 'pear', 'fig']

Two things are new here:

  • builtins is the Python module that holds Python’s built-in functions (sorted, len, max, int…). Import it whenever you need one of them.
  • Python.list(...) makes a Python list from Mojo values. Passing key=builtins.len hands Python’s own len function to sorted, just like sorted(words, key=len) in Python.

Anything that comes back from Python has the same methods it has in Python. A Python date, for example:

from std.python import Python
def main() raises:
var datetime = Python.import_module("datetime")
var day = datetime.date(2026, 11, 26)
print(day.strftime("%A, %d %B %Y"))
print(day.year)
var later = day + datetime.timedelta(days=10)
print(later)

Output:

Thursday, 26 November 2026
2026
2026-12-06

day.strftime(...) is a method call, day.year reads an attribute, and day + datetime.timedelta(days=10) uses Python’s own + for dates. Mojo passes each of these on to Python and wraps whatever comes back.

You can import a .py file you wrote, too. Say your project looks like this:

my-project/
├── main.mojo
└── pylib/
└── greetings.py

and greetings.py has two functions:

def hello(name):
return f"Hello, {name}! Greetings from Python."
def shout(text, times=1):
return (text.upper() + "!") * times

Python only finds modules in folders on its search path, so add the folder first with Python.add_to_path():

from std.python import Python
def main():
try:
Python.add_to_path("pylib")
var greetings = Python.import_module("greetings")
print(greetings.hello("Mojo"))
print(greetings.shout("hi", times=3))
except e:
print("Python error:", e)

Run it from the my-project folder:

Terminal window
mojo main.mojo

Output:

Hello, Mojo! Greetings from Python.
HI!HI!HI!

A relative path like "pylib" is relative to the folder you run the program from, not to where main.mojo lives. Run it from somewhere else and Python won’t find the module. Because the code catches the error, you get a clear message instead of a crash:

Python error: No module named 'greetings'

Sometimes you just need one Python expression. Python.evaluate() runs it and gives you the result:

from std.python import Python
def main() raises:
print(Python.evaluate("[n * n for n in range(5)]"))
print(Python.evaluate("'hello, mojo'.title()"))

Output:

[0, 1, 4, 9, 16]
Hello, Mojo

With file=True, it runs a whole piece of Python source as a new module and gives you that module, so you can keep a few small Python helpers inside your Mojo file:

from std.python import Python
def main() raises:
var helpers = Python.evaluate(
"""
def area(width, height):
return width * height
def describe(n):
return "even" if n % 2 == 0 else "odd"
""",
file=True,
name="helpers",
)
print(helpers.area(3, 4))
print(helpers.describe(7))

Output:

12
odd

The triple-quoted string is ordinary Python, so it uses Python’s indentation rules inside the string. For more than a few lines, a real .py file is easier to read and edit.

A Python exception turns into a Mojo error that you can catch with try/except:

from std.python import Python
def main():
try:
var builtins = Python.import_module("builtins")
var n = builtins.int("forty-two")
print(n)
except e:
print("Python said:", e)

Output:

Python said: invalid literal for int() with base 10: 'forty-two'

You get Python’s message, but you can’t write except ValueError: the way you would in Python. Mojo allows one except per try (see Mojo Try and Except). If you need to tell errors apart, check the message, or do the risky part in Python and return a result your Mojo code can test.

Python’s print and Mojo’s print both write to the terminal, so mixing them looks fine while you’re testing:

from std.python import Python
def main() raises:
var builtins = Python.import_module("builtins")
print("Mojo 1")
builtins.print("Python 2", flush=True)
print("Mojo 3")

Output:

Mojo 1
Python 2
Mojo 3

Notice the flush=True. Python keeps its output in a buffer when it isn’t writing to a terminal, for example when you send the output to a file. In our tests, without flush=True, Python’s line never reached the file at all:

Terminal window
mojo main.mojo > out.txt
cat out.txt
Mojo 1
Mojo 3

Use json to turn this text into a dictionary: '{"b": 2, "a": 1}'. Add a key "c" with the value 3, then print it with the keys sorted and an indent of 4.

Hint: json.dumps takes indent= and sort_keys=True. Setting a key works like Python: data["c"] = 3.

Show solution
from std.python import Python
def main() raises:
var json = Python.import_module("json")
var data = json.loads('{"b": 2, "a": 1}')
data["c"] = 3
print(json.dumps(data, indent=4, sort_keys=True))

Output:

{
"a": 1,
"b": 2,
"c": 3
}

data is a real Python dictionary, so assigning a new key changes it in place. Both keyword arguments go straight to Python’s json.dumps.

With Python’s datetime module, work out how many days there are from 26 November 2026 to 1 January 2027, and print 36 days.

Hint: subtracting two datetime.date objects gives a timedelta, which has a .days attribute.

Show solution
from std.python import Python
def main() raises:
var datetime = Python.import_module("datetime")
var start = datetime.date(2026, 11, 26)
var end = datetime.date(2027, 1, 1)
var gap = end - start
print(gap.days, "days")

Output:

36 days

The subtraction runs in Python and returns a timedelta. gap.days reads its attribute, and Mojo’s print puts the two values together with a space.

Write a program that uses Python’s int() to convert the texts "12", "x7" and "30". For each one, print the number, or not a number: x7 when it fails. Keep the loop going after a failure.

Hint: put a try/except inside the loop, around the builtins.int(...) call. A list of Python strings is easy to make with Python.list("12", "x7", "30").

Show solution
from std.python import Python
def main() raises:
var builtins = Python.import_module("builtins")
var texts = Python.list("12", "x7", "30")
for text in texts:
try:
print(builtins.int(text))
except:
print("not a number:", text)

Output:

12
not a number: x7
30

Looping over a Python list gives you each item as a PythonObject. Because the try sits inside the loop, a failure only skips that one item.

  • Python.import_module("json") is import json. You import whole modules and use them through the variable.
  • Call Python functions and methods as usual, keyword arguments included (indent=2, reverse=True).
  • Python.import_module("builtins") gives you sorted, int, max and the other built-in functions.
  • For your own .py files, Python.add_to_path("folder") adds a folder (relative to where you run the program).
  • Python.evaluate() runs an expression, or a whole module with file=True.
  • Python exceptions become Mojo errors; catch them with try/except and read the message.
  • Python’s print output can go missing when redirected: use flush=True or print from Mojo.

Next up: Mojo with NumPy, installing NumPy and moving data between NumPy arrays and Mojo.

Quick check

1. How do you call Python's built-in sorted() from Mojo?
2. Which of these works in Mojo 1.2?
3. You run mojo main.mojo from a different folder, and Python.add_to_path("pylib") no longer finds your module. Why?
4. A Python function raises ValueError. How do you catch it in Mojo?