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.
Variables
Section titled “Variables”name = "Ann"age = 36age = age + 1price = 9.99print(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.99What 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.
Functions with types
Section titled “Functions with 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!12Default 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] 490 60True[180, 150, 164, 120]Three things to watch:
- Say it’s a
List.var scores = [90, 75, 82]on its own makes a fixed-sizeArray, which can’t grow. WritingList[Int]gives you the list you know from Python. - One element type. A
List[Int]only holdsIntvalues. - No negative indexes.
scores[-1]is a compile error. Usescores[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.
Dictionaries
Section titled “Dictionaries”ages = {"Ann": 31, "Bo": 25}ages["Cy"] = 40for 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 31Bo 25Cy 400TrueA 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 = 3while n > 0: print("countdown", n) n -= 1def 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 -= 1Output:
0 apple1 pear2 figcountdown 3countdown 2countdown 1Loops 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.
Classes become structs
Section titled “Classes become structs”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_initstruct 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 4What’s new here:
- Fields are declared at the top with
var name: String. @fieldwise_initwrites 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. Withoutmut,self.age += 1is a compile error (expression must be mutable).String(self.age)instead ofstr(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.
Errors
Section titled “Errors”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:
42Error: age cannot be negativeError: 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.
Imports
Section titled “Imports”import mathfrom math import sqrtprint(math.pi)print(sqrt(16))from std.math import sqrt, pi
def main(): print(pi) print(sqrt(16.0))Output:
3.1415926535897934.0Mojo’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.
Calling Python from Mojo
Section titled “Calling Python from Mojo”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.
Cheat list
Section titled “Cheat list”| 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") |
Practice
Section titled “Practice”1. Port a small function
Section titled “1. Port a small function”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: 6The 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.
2. A class becomes a struct
Section titled “2. A class becomes a struct”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_initstruct 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:
3add_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 withlen(xs) - 1. Dict[K, V]has fixed types; loop over.items()and use.keyand.value.- Structs replace classes: declared fields,
@fieldwise_init, andmut selffor methods that change things. - Functions that can fail are marked
raises; you still usetry/except. - The standard library is under
std., and Python modules come in withPython.import_module.
Next up: Mojo vs Rust & C++, how Mojo compares with the other fast languages.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Mojo tips for Python developers: the official guide to Python habits that change in Mojo.
- Mojo language basics: the manual’s overview of variables, functions, structs and more.
- Mojo structs: how structs work and how they differ from Python classes.
- Errors, error handling, and context managers:
raises,tryandexceptin Mojo. - Calling Python from Mojo: importing and using Python modules.