What this is about
The fastest way to see a new language is to put it next to one you know. Here are two small tasks, each written twice. The first adds up numbers. The second reads options from a command line. In both, the Mojo version looks like a close cousin of the Python one.
You will finish this article able to port a small Python function to Mojo by hand.
Why it matters
If you know Python, you already know most of Mojo's shape. The parts that are new are few, and they are the same parts every time. Learn them once and you can read any Mojo file in our repositories.
Task one: add the numbers from 1 to n
Python:
def total(n):
s = 0
for i in range(1, n + 1):
s += i
return s
print(total(10))
Mojo:
def total(n: Int) -> Int:
var s = 0
for i in range(1, n + 1):
s += i
return s
def main():
print(total(10))
Both print 55. We ran the Mojo one on Mojo 1.2.0 and the Python one on Python 3.
What changed:
- Types on the signature.
n: Intand-> Inttell the compiler what goes in and what comes out. varfor a new name. The first time you creates, you writevar s = 0.- A
mainfunction. Python runs the file from top to bottom. Mojo starts atmain. - A compile step.
mojo run total.mojocompiles first and then runs, so any mistake in the file shows up before anything prints.
What stayed the same: the indent, the for loop, range, +=, return and print. Even division behaves the same way. In both languages 7 / 2 gives 3.5 and 7 // 2 gives 3. We ran that too.
Where Mojo says no and Python says nothing
Python does not check type hints when it runs. This line runs without complaint:
n: int = "five"
In Mojo the same idea stops at compile time:
def main():
var n: Int = "five"
print(n)
error: cannot implicitly convert 'StringLiteral["five"]' value to 'Int'
This is the main trade. You write a little more, and you hear about the mistake earlier.
Task two: read options from the command line
Python's argparse:
import argparse
p = argparse.ArgumentParser("greet")
p.add_argument("name")
p.add_argument("--times", type=int, default=1)
p.add_argument("-q", "--quiet", action="store_true")
ns = p.parse_args(["ada", "--times", "3", "-q"])
print(ns.name, ns.times, ns.quiet)
Mojo, with our mojo-args library, which copies argparse's behavior:
from args import ArgumentParser
def main() raises:
var p = ArgumentParser("greet")
p.add_argument("name")
p.add_argument("--times", type="int", default="1")
p.add_argument("-q", "--quiet", action="store_true")
var ns = p.parse_args(["ada", "--times", "3", "-q"])
print(ns.get_str("name"), ns.get_int("times"), ns.get_bool("quiet"))
Our run printed ada 3 True. A second call with only ["bo"] printed bo 1 False, the defaults.
What changed here:
- The import reads
from args import ArgumentParser. - Values come out through
get_str,get_intandget_bool. Mojo wants to know the type you want. mainsaysraises, because parsing can fail and Mojo makes you say so.typeanddefaultare given as text, such astype="int".
What stayed the same: the names add_argument, parse_args, store_true and the shape of the code. We built the library this way on purpose. If you know argparse, you can guess most of it.
When we passed --times x, the library stopped with argument --times: invalid int value: 'x', which is the same text argparse prints.
A checklist for porting a small function by hand
When you port a Python function to Mojo, go through these steps in order.
- Copy the Python function into a
.mojofile and changedef name(args):to include a type for each argument. - Add the return type after
->. - Add
varthe first time each new name is created. - Wrap the call in a
def main():so the program has a place to start. - Run it with
mojo run. Read the first error. Fix it. Run it again. - Compare the answer with the Python version on at least three inputs, one of them an edge case, such as zero or an empty value.
That last step is the one people skip. A port that compiles has been accepted by the compiler. It has not been checked against the original. The next articles in this series show how to do that check properly.
The one thing we did not measure
We did not time these toy programs. Ten numbers and four options run in no time in either language. The speed gaps in our READMEs come from much bigger jobs, such as 200,000 parses in a row. A toy is for learning the shape. A benchmark is a different test.
Words you may not know
- Type hint: a note in Python code about what type a value should be. Python does not enforce it.
- Signature: the first line of a function, with its name, inputs and output.
- Compile time: the moment before the program runs, when the compiler reads your file.
- Raises: a mark that says a function might stop with an error.
- Default: the value a setting takes when you do not give one.
Try it
- Port one small function of your own using the four changes above. Run it with
mojo run. - See the mojo-args repository for the full list of what it supports.
- Browse the mojo-libs table for a library that matches a Python module you use.
Read next
- Installing Mojo and running your first program if the compile step is new to you.

Kommentare
Noch keine Kommentare.
Anmelden um zu kommentieren.