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.
Importing a module
Section titled “Importing a module”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:
AdaMojo2json.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. Importjsonand writejson.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
raisesor atryblock.
Calling functions with keyword arguments
Section titled “Calling functions with keyword arguments”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:
builtinsis 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. Passingkey=builtins.lenhands Python’s ownlenfunction tosorted, just likesorted(words, key=len)in Python.
Calling methods on Python objects
Section titled “Calling methods on Python objects”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 202620262026-12-06day.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.
Using your own Python file
Section titled “Using your own Python file”You can import a .py file you wrote, too. Say your project looks like this:
my-project/├── main.mojo└── pylib/ └── greetings.pyand greetings.py has two functions:
def hello(name): return f"Hello, {name}! Greetings from Python."
def shout(text, times=1): return (text.upper() + "!") * timesPython 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:
mojo main.mojoOutput:
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'Running a bit of Python code
Section titled “Running a bit of Python code”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, MojoWith 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:
12oddThe 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.
When Python raises an exception
Section titled “When Python raises an exception”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.
Output from Python’s print
Section titled “Output from Python’s print”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 1Python 2Mojo 3Notice 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:
mojo main.mojo > out.txtcat out.txtMojo 1Mojo 3Practice
Section titled “Practice”1. Pretty JSON
Section titled “1. Pretty JSON”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.
2. Days until a date
Section titled “2. Days until a date”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 daysThe 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.
3. Safe conversion
Section titled “3. Safe conversion”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:
12not a number: x730Looping 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")isimport 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 yousorted,int,maxand the other built-in functions.- For your own
.pyfiles,Python.add_to_path("folder")adds a folder (relative to where you run the program). Python.evaluate()runs an expression, or a whole module withfile=True.- Python exceptions become Mojo errors; catch them with
try/exceptand read the message. - Python’s
printoutput can go missing when redirected: useflush=Trueor print from Mojo.
Next up: Mojo with NumPy, installing NumPy and moving data between NumPy arrays and Mojo.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Calling Python from Mojo: the manual’s guide to
import_module,add_to_pathand Python versions. - Python struct reference:
import_module,add_to_path,evaluate,list,dictand more. - PythonObject reference: every operator and method a Python value supports in Mojo.
- Python’s built-in functions: what you can reach through the
builtinsmodule.