Mojo Python Types
Every time Mojo and Python talk to each other, values cross a border. A Mojo Int has to become a Python int, and a Python string has to become a Mojo String before most Mojo code can use it. Some of this happens by itself, some you do by hand. This page shows both directions, the PythonObject type that sits in the middle, and the mistakes that are easy to make.
Every example on this page was checked with Mojo 1.2 and Python 3.13.
Mojo values going into Python
Section titled “Mojo values going into Python”When you pass a Mojo number, Bool or String to a Python function, Mojo converts it for you. Python’s type() shows what arrives:
from std.python import Python
def main() raises: var builtins = Python.import_module("builtins") var count: Int = 7 var price: Float64 = 2.5 var small: UInt8 = 200 var ok = True var name: String = "Mojo" print(builtins.type(count)) print(builtins.type(price)) print(builtins.type(small)) print(builtins.type(ok)) print(builtins.type(name))Output:
<class 'int'><class 'float'><class 'int'><class 'bool'><class 'str'>Every Mojo integer type (Int, UInt8, Int32 and the rest) becomes a Python int, both float types become float, Bool becomes bool, and String becomes str. Python has only one integer type and one float type, so the size information is gone on the Python side.
The manual’s Python types page lists these automatic conversions: integers, floats, booleans and strings. Collections like List and Dict are not on that list. You’ll convert those yourself, further down.
What PythonObject is
Section titled “What PythonObject is”Anything you get back from Python is a PythonObject: a Mojo wrapper around a Python value. It can hold any Python value at all (a number, a list, a NumPy array, a module) and passes everything you do with it on to Python: +, [], .method(), len(), print().
You can also make one yourself. Import it from std.python, and use literals with a type annotation for lists, dicts and sets:
from std.python import Python, PythonObject
def main() raises: var answer = PythonObject(42) var greeting = PythonObject("hello") var items: PythonObject = [1, "two", 3.0] var ages: PythonObject = {"Ada": 36, "Linus": 21} var colours: PythonObject = {"red", "blue", "red"} var point = Python.tuple(3, 4) print(answer, greeting) print(items) print(ages) print(len(colours)) print(point)Output:
42 hello[1, 'two', 3.0]{'Ada': 36, 'Linus': 21}2(3, 4)Because the variables are declared as PythonObject, Mojo builds real Python objects from the literals: a list (which, as in Python, can mix types), a dict, and a set, which drops the repeated "red" and so has 2 items. For tuples there’s Python.tuple(...), and Python.list(...) and Python.dict() work too, as you saw on the earlier pages. Note that PythonObject needs its own import; from std.python import Python alone isn’t enough.
Python values coming back to Mojo
Section titled “Python values coming back to Mojo”A PythonObject is fine for printing or passing back to Python, but most Mojo code wants real Mojo types. Convert with the type’s name and the py= keyword:
from std.python import PythonObject
def main() raises: var py_count = PythonObject(41) var py_price = PythonObject(2.5) var py_name = PythonObject("Mojo") var py_flag = PythonObject(True)
var count = Int(py=py_count) + 1 var price = Float64(py=py_price) * 2 var name = String(py=py_name) + "!" var flag = Bool(py=py_flag) print(count, price, name, flag)Output:
42 5.0 Mojo! TrueNow count is a real Mojo Int, name a real String, and so on. Mojo never does this conversion silently. Try to put a PythonObject straight into an Int variable and it refuses:
from std.python import PythonObject
def main() raises: var py_count = PythonObject(41) var count: Int = py_count print(count)hello.mojo:5:22: error: cannot implicitly convert 'PythonObject' value to 'Int' var count: Int = py_count ^~~~~~~~mojo: error: failed to parse the provided Mojo source moduleThat’s on purpose: a Python value could be anything, so you say which Mojo type you want and accept that it might fail.
When a conversion fails
Section titled “When a conversion fails”A conversion can fail while the program runs, so it raises an error you can catch. Here’s Int(py=...) with four different Python values:
from std.python import Python
def main() raises: var values = Python.list("12", 3.9, "abc", Python.evaluate("2 ** 100")) for v in values: try: print(Int(py=v)) except e: print("error:", e)Output:
123error: invalid literal for int() with base 10: 'abc'error: Python int too large to convert to C ssize_tInt(py=...) behaves like Python’s int(): it accepts the text "12", and it cuts 3.9 down to 3 (no rounding). Text that isn’t a number fails with Python’s usual message. The last one is the interesting case: 2 ** 100 is fine in Python, whose integers have no size limit, but it doesn’t fit in a 64-bit Mojo Int.
Float64(py=...) is stricter. It takes numbers, but not text:
from std.python import Python
def main() raises: var values = Python.list(3, "2.5", None) for v in values: try: print(Float64(py=v)) except e: print("error:", e)Output:
3.0error: must be real number, not strerror: must be real number, not NoneTypeIf you have text with a decimal number in it, convert it on the Python side first (builtins.float(text)) or with Mojo’s own Float64(String(py=text)). And String(py=...) accepts any Python value at all: it uses Python’s str(), so String(py=PythonObject(42)) gives "42".
True, False and None
Section titled “True, False and None”PythonObject follows Python’s rules for truth: an empty list, 0, "" and None count as false. Python’s None is Python.none(), and you test for it with is, as you would in Python:
from std.python import Python, PythonObject
def main() raises: var empty = Python.list() var nothing = Python.none() var word = PythonObject("hi") if not empty: print("an empty list is falsy") if nothing is Python.none(): print("it's None") if word: print("non-empty text is truthy")
var x = PythonObject(5) var bigger = x > 3 print(bigger, Python.type(bigger))Output:
an empty list is falsyit's Nonenon-empty text is truthyTrue <class 'bool'>Notice the last line: comparing a PythonObject gives you a Python bool (still a PythonObject), because the comparison ran in Python. It works in an if right away; when you need a Mojo Bool to store, write Bool(x > 3).
Converting lists and dicts
Section titled “Converting lists and dicts”List and Dict don’t cross the border by themselves, so you copy them item by item. Python to Mojo means converting each item; Mojo to Python means appending or setting each item:
from std.python import Python
def main() raises: var py_nums = Python.list(3, 1, 2) var nums = List[Int]() for item in py_nums: nums.append(Int(py=item)) print(nums)
var prices = Dict[String, Float64]() prices["apple"] = 1.25 prices["pear"] = 0.8 var py_prices = Python.dict() for entry in prices.items(): py_prices[entry.key] = entry.value print(py_prices)Output:
[3, 1, 2]{'apple': 1.25, 'pear': 0.8}The first print is a Mojo List[Int], the second a Python dict. Both prints look much the same, but only the first one can go into Mojo functions that expect a List[Int]. (To convert a dictionary from Python to Mojo, loop over its keys with for key in py_dict: and convert each key and value.)
For big amounts of numeric data this copying is slow. If the data lives in a NumPy array, Mojo with NumPy shows how to share it without copying.
Cheat sheet
Section titled “Cheat sheet”| You have | You want | Write |
|---|---|---|
Mojo Int, Float64, Bool, String |
Python value | Nothing, just pass it (or PythonObject(x)) |
| A few values | Python list / tuple | Python.list(a, b), Python.tuple(a, b), or var l: PythonObject = [a, b] |
| Key-value pairs | Python dict | Python.dict() then d[key] = value, or var d: PythonObject = {...} |
PythonObject |
Mojo Int / Float64 / Bool / String |
Int(py=x), Float64(py=x), Bool(py=x), String(py=x) |
| Python list | Mojo List |
Loop and append(Int(py=item)) |
Mojo List / Dict |
Python list / dict | Loop and append(...) / d[key] = value |
Python None |
Test for it | x is Python.none() |
Practice
Section titled “Practice”1. Add up a Python list
Section titled “1. Add up a Python list”You get this Python list from a library: Python.list(4, "5", 6.7). Convert every item to a Mojo Int and print the total. It should print 15.
Hint: remember that Int(py=...) accepts text with digits and drops the part after the decimal point.
Show solution
from std.python import Python
def main() raises: var values = Python.list(4, "5", 6.7) var total = 0 for v in values: total += Int(py=v) print(total)Output:
15Int(py=...) works like Python’s int(), so "5" becomes 5 and 6.7 becomes 6. The sum happens in Mojo, on real Int values: 4 + 5 + 6.
2. Mojo dict to JSON
Section titled “2. Mojo dict to JSON”Make a Mojo Dict[String, Int] with "apples": 3 and "pears": 5. Copy it into a Python dict and print it as JSON with Python’s json.dumps.
Hint: loop over fruit.items() and set py_dict[entry.key] = entry.value, then call json.dumps(py_dict).
Show solution
from std.python import Python
def main() raises: var fruit = Dict[String, Int]() fruit["apples"] = 3 fruit["pears"] = 5 var py_fruit = Python.dict() for entry in fruit.items(): py_fruit[entry.key] = entry.value var json = Python.import_module("json") print(json.dumps(py_fruit))Output:
{"apples": 3, "pears": 5}Each String key and Int value converts to Python by itself when you assign it, so the copy is just one line in the loop. json.dumps only understands Python objects, which is why the copy is needed.
- Mojo integers, floats,
BoolandStringturn into Python values by themselves. PythonObjectwraps any Python value and passes operations to Python. Import it fromstd.python.- Make Python collections with
var l: PythonObject = [...],{...}, orPython.list(),Python.tuple(),Python.dict(). AvoidPythonObject([...]). - Convert back with
Int(py=x),Float64(py=x),Bool(py=x),String(py=x); there’s no automatic conversion. - Conversions can fail at run time: wrap values from outside in
try. ListandDictdon’t convert by themselves: copy them with a loop.
Next up: Mojo GPU Basics, what a GPU is good at and what you need to program one with Mojo.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Python types: the manual’s page on conversions in both directions and on
PythonObject. - PythonObject reference: every operator, method and initializer.
- ConvertibleFromPython: the trait behind
Int(py=...)and friends. - Python struct reference:
Python.list,Python.dict,Python.tuple,Python.noneandPython.type.