Skip to content

Mojo for Python Developers

If you already write Python, you don’t have to learn Mojo from zero. This page shows the things you do every day in Python next to the same thing in Mojo, so you can see exactly what changes. Each pair prints the same output.

It’s a quick tour, not the full story. Every section links to the lesson that covers the topic properly.

name = "Ann"
age = 36
age = age + 1
price = 9.99
print(name, age, price)
def main():
var name = "Ann"
var age = 36
age = age + 1
var price: Float64 = 9.99
print(name, age, price)

Output:

Ann 37 9.99

What changes:

  • The code lives in def main():. Mojo doesn’t run code at the top level of a file.
  • A new variable needs var. Changing it later (age = age + 1) doesn’t.
  • You can add a type, like var price: Float64. If you don’t, Mojo works it out from the value.
  • Once a variable has a type, it keeps it. age = "old" would be a compile error.

More in Mojo Variables and Mojo Data Types.

def greet(name, greeting="Hello"):
return greeting + ", " + name + "!"
def area(width, height):
return width * height
print(greet("Ann"))
print(greet("Bo", greeting="Hi"))
print(area(3, 4))
def greet(name: String, greeting: String = "Hello") -> String:
return greeting + ", " + name + "!"
def area(width: Int, height: Int) -> Int:
return width * height
def main():
print(greet("Ann"))
print(greet("Bo", greeting="Hi"))
print(area(3, 4))

Output:

Hello, Ann!
Hi, Bo!
12

Default values and keyword arguments work like Python. The difference is the types: every argument has one, and -> String says what comes back. A function with no -> returns nothing.

One more change you’ll meet soon: by default, a function can’t change its arguments. They’re read-only, which is safe and fast. You’ll see how to allow changes with mut in Mojo Function Arguments and Mojo Argument Conventions.

scores = [90, 75, 82]
scores.append(60)
print(scores, len(scores))
print(scores[0], scores[-1])
print(75 in scores)
doubled = [s * 2 for s in scores]
print(doubled)
def main():
var scores: List[Int] = [90, 75, 82]
scores.append(60)
print(scores, len(scores))
print(scores[0], scores[len(scores) - 1])
print(75 in scores)
var doubled = [s * 2 for s in scores]
print(doubled)

Output:

[90, 75, 82, 60] 4
90 60
True
[180, 150, 164, 120]

Three things to watch:

  • Say it’s a List. var scores = [90, 75, 82] on its own makes a fixed-size Array, which can’t grow. Writing List[Int] gives you the list you know from Python.
  • One element type. A List[Int] only holds Int values.
  • No negative indexes. scores[-1] is a compile error. Use scores[len(scores) - 1] for the last item.

The official tips for Python developers list more of these surprises. Lists get their own lesson in Mojo Lists.

ages = {"Ann": 31, "Bo": 25}
ages["Cy"] = 40
for name, age in ages.items():
print(name, age)
print(ages.get("Dee", 0))
print("Bo" in ages)
def main():
var ages: Dict[String, Int] = {"Ann": 31, "Bo": 25}
ages["Cy"] = 40
for item in ages.items():
print(item.key, item.value)
print(ages.get("Dee", 0))
print("Bo" in ages)

Output:

Ann 31
Bo 25
Cy 40
0
True

A Mojo Dict has a fixed key type and value type, here String keys and Int values. When you loop over .items(), each item has a .key and a .value instead of being a pair you unpack.

fruits = ["apple", "pear", "fig"]
for i, fruit in enumerate(fruits):
print(i, fruit)
n = 3
while n > 0:
print("countdown", n)
n -= 1
def main():
var fruits: List[String] = ["apple", "pear", "fig"]
for i, fruit in enumerate(fruits):
print(i, fruit)
var n = 3
while n > 0:
print("countdown", n)
n -= 1

Output:

0 apple
1 pear
2 fig
countdown 3
countdown 2
countdown 1

Loops are the part that changes least. for, range(), enumerate(), while, break and continue all work the way you expect. Details in Mojo For and Mojo While.

Mojo has no class (yet). You use a struct, which looks similar but is fixed when the program is compiled: you list the fields and their types up front, and you can’t add new fields later.

class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def birthday(self):
self.age += 1
def describe(self):
return self.name + " is " + str(self.age)
rex = Dog("Rex", 3)
rex.birthday()
print(rex.describe())
@fieldwise_init
struct Dog:
var name: String
var age: Int
def birthday(mut self):
self.age += 1
def describe(self) -> String:
return self.name + " is " + String(self.age)
def main():
var rex = Dog("Rex", 3)
rex.birthday()
print(rex.describe())

Output:

Rex is 4

What’s new here:

  • Fields are declared at the top with var name: String.
  • @fieldwise_init writes the __init__ for you: it takes the fields in order. You can still write your own __init__ when you need one.
  • mut self: a method that changes the struct says so. Without mut, self.age += 1 is a compile error (expression must be mutable).
  • String(self.age) instead of str(self.age).

There’s also no inheritance. Shared behavior comes from traits instead. And you can’t print(rex) until you teach Dog how to print itself. All of that comes in Mojo Structs, Mojo Traits and Mojo Printing Your Types.

def parse_age(text):
age = int(text)
if age < 0:
raise ValueError("age cannot be negative")
return age
for text in ["42", "-1", "abc"]:
try:
print(parse_age(text))
except ValueError as e:
print("Error:", e)
def parse_age(text: String) raises -> Int:
var age = Int(text)
if age < 0:
raise Error("age cannot be negative")
return age
def main():
var inputs: List[String] = ["42", "-1", "abc"]
for text in inputs:
try:
print(parse_age(text))
except e:
print("Error:", e)

Output:

42
Error: age cannot be negative
Error: String is not convertible to integer with base 10: 'abc'

(Python’s last line says invalid literal for int() with base 10: 'abc' instead.)

try, except and raise look the same. The big difference is raises in the signature: a Mojo function can only raise an error if it says so. Here parse_age says raises, and main handles the error with try, so main doesn’t need it. There’s one general error type, Error, and you write except e: rather than naming an exception class. More in Mojo Errors and Mojo Try/Except.

import math
from math import sqrt
print(math.pi)
print(sqrt(16))
from std.math import sqrt, pi
def main():
print(pi)
print(sqrt(16.0))

Output:

3.141592653589793
4.0

Mojo’s standard library lives under std., so Python’s math becomes std.math. Everyday things like print, len, range, Int, String, List and Dict need no import at all. Your own files are modules too; see Mojo Modules & Packages.

When you need a Python library, you can import it from Mojo:

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

Output:

Ann
['Python', 'Mojo']

Python.import_module("json") is Mojo’s way of writing import json. What comes back are Python objects, and the code runs in a real Python interpreter, so anything installed in your environment works. Notice the Python-style quotes in ['Python', 'Mojo']: that list is printed by Python, not Mojo. The Calling Python from Mojo page in the manual has the details, and so does Mojo Calling Python.

Python Mojo
x = 5 (new name) var x = 5
def f(a, b): def f(a: Int, b: Int) -> Int:
[1, 2, 3] (a list) var xs: List[Int] = [1, 2, 3]
xs[-1] xs[len(xs) - 1]
{"a": 1} var d: Dict[String, Int] = {"a": 1}
str(42) String(42)
class Dog: struct Dog: with declared fields
def change(self): def change(mut self):
raise ValueError("...") raise Error("...") in a function marked raises
import math from std.math import ...
import numpy as np var np = Python.import_module("numpy")

Port this Python to Mojo. It should print Total: 6.

def total(numbers):
result = 0
for n in numbers:
result += n
return result
print("Total:", total([1, 2, 3]))

Hint: give numbers the type List[Int], give the function a return type, and build the list in main first.

Show solution
def total(numbers: List[Int]) -> Int:
var result = 0
for n in numbers:
result += n
return result
def main():
var nums: List[Int] = [1, 2, 3]
print("Total:", total(nums))

Output:

Total: 6

The loop is unchanged. The new parts are the types on the argument and the result, var for result, and making the list a typed List[Int] variable.

Write a struct Counter with one field count: Int, a method add_one that increases it, and use it to print 3 after calling add_one three times.

Hint: use @fieldwise_init, and remember the method changes the struct.

Show solution
@fieldwise_init
struct Counter:
var count: Int
def add_one(mut self):
self.count += 1
def main():
var c = Counter(0)
for _ in range(3):
c.add_one()
print(c.count)

Output:

3

add_one changes self, so it takes mut self. @fieldwise_init gives you Counter(0) for free.

  • Code goes in functions, and the program starts at def main():.
  • New variables need var; arguments and results get types.
  • Write List[Int] to get a growable list, and count from the end with len(xs) - 1.
  • Dict[K, V] has fixed types; loop over .items() and use .key and .value.
  • Structs replace classes: declared fields, @fieldwise_init, and mut self for methods that change things.
  • Functions that can fail are marked raises; you still use try/except.
  • The standard library is under std., and Python modules come in with Python.import_module.

Next up: Mojo vs Rust & C++, how Mojo compares with the other fast languages.

Quick check

1. What does var scores = [90, 75, 82] create in Mojo?
2. A struct method needs to change one of the struct's fields. How do you write its first argument?
3. How do you get the last item of a Mojo list xs?
4. What do you add to a function that can raise an error?