Mojo Modules & Packages
Once a program grows past a hundred lines or so, one big file gets hard to work with. Mojo lets you split code into modules (one file each) and group modules into packages (a folder). If you’ve used Python’s import, most of this will feel familiar, with a few differences that this page points out.
Every example here uses more than one file, so you can’t paste it into a single file and run it. Each one was built as a real folder and run with Mojo 1.2 on Linux; what’s under “You’ll see” is the real output.
A module is just a file
Section titled “A module is just a file”Any .mojo file can be a module. Here’s geometry.mojo, with a constant and two functions:
comptime PI = 3.14159
def circle_area(radius: Float64) -> Float64: return PI * radius * radius
def square_area(side: Float64) -> Float64: return side * sideNext to it, in the same folder, put main.mojo:
from geometry import circle_area, square_area
def main(): print(circle_area(2.0)) print(square_area(3.0))Run the file that has main:
mojo run main.mojoYou’ll see:
12.566369.0The module’s name is the file name without .mojo. from geometry import circle_area, square_area pulls those two names into main.mojo, so you can call them directly. Mojo finds geometry.mojo because it sits in the same folder as main.mojo.
geometry.mojo has no main, so it can’t run on its own:
mojo run geometry.mojoYou’ll see:
mojo: error: module does not define a `main` functionThat’s normal. A module is a box of tools for other files; only one file, the one you run, needs main.
Four ways to import
Section titled “Four ways to import”You’ve seen from ... import .... There are a few more ways to write an import, and they all work with your own modules and the standard library alike:
| Import | How you use it | When it’s handy |
|---|---|---|
from geometry import circle_area |
circle_area(2.0) |
You use a few names a lot |
import geometry |
geometry.circle_area(2.0) |
You want to see where each name comes from |
import geometry as geo |
geo.circle_area(2.0) |
The module name is long |
from geometry import circle_area as area |
area(2.0) |
You want a shorter or clearer name |
Here are three of them in one file:
import geometryimport geometry as geofrom geometry import circle_area as area
def main(): print(geometry.square_area(4.0)) print(geo.PI) print(area(1.0))You’ll see:
16.03.141593.14159There’s also from geometry import *, which pulls in every name. It works, but it hides where names come from, so most people avoid it outside quick experiments. And from std.math import sqrt, which you saw in Mojo Syntax, is the same idea: std is a package that comes with Mojo, and math is a module in it.
When two modules use the same name
Section titled “When two modules use the same name”Say metric.mojo and imperial.mojo both have a function called label. In Python, importing both with from ... import label silently keeps the second one. Mojo refuses:
from metric import labelfrom imperial import label
def main(): print(label())You’ll see:
clash.mojo:2:22: error: import of 'label' is ambiguousfrom imperial import label ^metric.mojo:1:5: note: 'label' declared hereimperial.mojo:1:5: note: 'label' also declared heremojo: error: failed to parse the provided Mojo source moduleFix it by keeping the module name in front (import metric, then metric.label()), or by renaming one of them: from imperial import label as imperial_label. Both were checked and print metric and imperial as you’d expect.
What a module can hold
Section titled “What a module can hold”A module can define functions, structs, traits and comptime constants. It can’t hold global variables or loose code that runs on import. This settings.mojo tries a global variable:
var debug = False
def is_debug() -> Bool: return debugAs soon as another file imports it, you get:
Imported from app.mojo:1:settings.mojo:1:1: error: global variables are not supported; move this into a function body or use 'comptime' to declare a constantvar debug = False^mojo: error: failed to parse the provided Mojo source moduleA line like print("loading") at the top of a module fails the same way (expressions must not appear at file scope). This is a real difference from Python, where top-level code runs the moment a module is imported. In Mojo, nothing runs on import. If you need a fixed value, use comptime; if you need a value that changes, create it in main and pass it to the functions that need it.
Packages: a folder of modules
Section titled “Packages: a folder of modules”When you have several related modules, put them in a folder. A folder with an __init__.mojo file in it is a package. Here’s a small one:
my-project/├── main.mojo└── mathkit/ ├── __init__.mojo (empty for now) ├── basic.mojo └── stats.mojomathkit/basic.mojo:
def add(a: Int, b: Int) -> Int: return a + b
def double(n: Int) -> Int: return n * 2mathkit/stats.mojo uses add from its neighbor. Inside a package, a leading dot means “a module in this same package”:
from .basic import add
def mean(nums: List[Int]) -> Float64: var total = 0 for n in nums: total = add(total, n) return Float64(total) / Float64(len(nums))From main.mojo, you name the package, a dot, then the module:
from mathkit.basic import add, doublefrom mathkit.stats import mean
def main(): var scores: List[Int] = [70, 85, 90] print(add(2, 3)) print(double(21)) print(mean(scores))You’ll see:
54281.66666666666667Shorter imports with __init__.mojo
Section titled “Shorter imports with __init__.mojo”__init__.mojo can be empty, but it’s also the package’s front door. Whatever it imports becomes available from the package name itself. Put this in mathkit/__init__.mojo:
from .basic import add, doublefrom .stats import meanNow main.mojo can skip the module names:
from mathkit import add, mean
def main(): var scores: List[Int] = [70, 85, 90] print(add(2, 3)) print(mean(scores))You’ll see:
581.66666666666667The standard library does the same. The manual’s example: map lives in the functional module of std.algorithm, but the package’s __init__.mojo re-exports it, so from std.algorithm import map works.
One thing that catches Python users: import mathkit doesn’t make the modules inside it reachable as mathkit.basic:
import mathkit
def main(): print(mathkit.add(2, 3)) print(mathkit.basic.double(4))You’ll see:
main.mojo:6:18: error: package 'mathkit' has no declaration 'basic' print(mathkit.basic.double(4)) ~~~~~~~^~~~~~mojo: error: failed to parse the provided Mojo source modulemathkit.add works (the __init__.mojo imported it), but the module itself isn’t attached. Ask for the module directly instead: from mathkit import basic, then call basic.double(4).
Where Mojo looks for imports
Section titled “Where Mojo looks for imports”Mojo finds modules in three kinds of places:
- The standard library, which is why its imports start with
std.. - The folder of the file you run. Not the folder you’re in:
mojo run app/main.mojofinds modules next toapp/main.mojo. - Any folder you add with
-I.
-I is useful when your code lives in one folder and the program that uses it lives in another:
my-project/├── app/│ └── main.mojo└── lib/ └── mathkit/ ├── __init__.mojo ├── basic.mojo └── stats.mojoWithout help, app/main.mojo can’t see mathkit:
mojo run app/main.mojoYou’ll see:
app/main.mojo:1:6: error: unable to locate module 'mathkit'from mathkit import add, mean ^mojo: error: failed to parse the provided Mojo source moduleAdd the lib folder with -I, and it works:
mojo run -I lib app/main.mojoYou’ll see:
581.66666666666667Put -I before the file name, like every option for Mojo itself; anything after the file name goes to your program. You can repeat -I for more folders, and mojo build takes it too. The Mojo Testing lesson uses the same trick to keep tests in their own folder.
Practice
Section titled “Practice”1. Split a converter
Section titled “1. Split a converter”Put two functions in convert.mojo: c_to_f (Celsius to Fahrenheit, c * 9 / 5 + 32) and f_to_c (the other way). Then write main.mojo in the same folder that prints c_to_f(100.0) and f_to_c(212.0).
Hint: convert.mojo has no main; main.mojo imports from convert.
Show solution
convert.mojo:
def c_to_f(c: Float64) -> Float64: return c * 9.0 / 5.0 + 32.0
def f_to_c(f: Float64) -> Float64: return (f - 32.0) * 5.0 / 9.0main.mojo:
from convert import c_to_f, f_to_c
def main(): print(c_to_f(100.0)) print(f_to_c(212.0))You’ll see:
212.0100.0Both files sit in one folder, so from convert import ... finds convert.mojo without any -I.
2. A package with a front door
Section titled “2. A package with a front door”Make a package text with two modules: loud.mojo with shout(s) (upper case plus !) and quiet.mojo with whisper(s) (lower case plus ...). Set up __init__.mojo so main.mojo can write from text import shout, whisper.
Hint: inside __init__.mojo, use relative imports that start with a dot.
Show solution
text/loud.mojo:
def shout(s: String) -> String: return s.upper() + "!"text/quiet.mojo:
def whisper(s: String) -> String: return s.lower() + "..."text/__init__.mojo:
from .loud import shoutfrom .quiet import whispermain.mojo, next to the text folder:
from text import shout, whisper
def main(): print(shout("hello")) print(whisper("GOOD NIGHT"))You’ll see:
HELLO!good night...__init__.mojo brings shout and whisper up to the package level, so main.mojo doesn’t need to know which module each one lives in.
- A module is a
.mojofile; its name is the file name. Only the file you run needsmain. - Import with
from m import name,import m, or rename withas. Two imports of the same name are a compile error, not a silent overwrite. - Modules hold functions, structs, traits and
comptimevalues. No globalvarand no top-level code, so nothing runs on import. - A package is a folder with an
__init__.mojofile. Inside it,from .module import nameimports a neighbor. - Whatever
__init__.mojoimports is reachable from the package name;import pkgalone doesn’t attach its modules. - Mojo looks in the standard library, the folder of the file you run, and any folder given with
-I(before the file name).
Next up: Mojo command-line arguments, reading what the user types after your program’s name.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Modules and packages: the official manual page on modules, packages,
__init__.mojoand precompiled packages. - mojo run: every option of
mojo run, including-I. - mojo precompile: turning a package folder into a single
.mojocfile. - Python’s modules tutorial: how Python does it, if you want to compare the details.