Skip to content

Mojo Context Managers

Some things need cleaning up after you use them: a file should be closed, a lock released, a “start” message matched with an “end”. The with statement does that for you. You hand it a context manager, and Mojo promises to run its cleanup code when the block ends, even if the block returns early or raises an error. It works much like Python’s with, and you can write your own context managers with two special methods.

The context manager you’ll use most is the file handle from open():

def main() raises:
with open("notes.txt", "w") as f:
f.write("first line\n")
f.write("second line\n")
with open("notes.txt", "r") as f:
print(f.read(), end="")

Output:

first line
second line

open() gives you a file handle, as f gives it a name, and when the indented block ends, Mojo closes the file. You never call f.close(). main is marked raises because opening a file can fail, for example when the folder doesn’t exist. The File I/O lesson covers reading and writing files in detail.

A context manager is a struct with two special methods:

  • __enter__ runs when the with block starts.
  • __exit__ runs when the block ends.

Here’s one that prints a header and a footer around some output:

@fieldwise_init
struct Section:
var title: String
def __enter__(self):
print("--- start:", self.title)
def __exit__(self):
print("--- end:", self.title)
def main():
with Section("report"):
print("line 1")
print("line 2")
print("after the block")

Output:

--- start: report
line 1
line 2
--- end: report
after the block

Section("report") creates the struct, with calls its __enter__, then runs the block, then calls __exit__. The struct is thrown away right after that.

The name after as gets whatever __enter__ returns. It doesn’t have to be the context manager itself. This one hands back a string of spaces for indenting:

@fieldwise_init
struct Indent:
var level: Int
def __enter__(self) -> String:
return " " * (self.level * 2)
def main():
print("menu")
with Indent(1) as pad:
print(pad + "drinks")
with Indent(2) as pad2:
print(pad2 + "coffee")
print(pad2 + "tea")

Output:

menu
drinks
coffee
tea

Indent has no __exit__ at all. That’s allowed: if there’s nothing to clean up, you only write __enter__. If __enter__ returns nothing, as in Section, you just leave out as.

The whole point of __exit__ is that it runs however the block ends. That includes continue, break and return:

@fieldwise_init
struct Tag:
var name: String
def __enter__(self):
print("<" + self.name + ">")
def __exit__(self):
print("</" + self.name + ">")
def first_even(nums: List[Int]) -> Int:
with Tag("search"):
for n in nums:
if n % 2 == 0:
return n
return -1
def main():
for i in range(3):
with Tag("li"):
if i == 1:
continue
print(i)
var nums: List[Int] = [3, 8, 5]
print(first_even(nums))

Output:

<li>
0
</li>
<li>
</li>
<li>
2
</li>
<search>
</search>
8

When i is 1, continue jumps out of the block, and </li> is still printed. In first_even, return n leaves the function from inside the with, and </search> still comes before the caller prints 8.

It also runs when the block raises an error. __exit__ runs first, and then the error goes on to the nearest try:

@fieldwise_init
struct Tag:
var name: String
def __enter__(self):
print("<" + self.name + ">")
def __exit__(self):
print("</" + self.name + ">")
def risky() raises:
raise Error("disk full")
def main():
try:
with Tag("log"):
print("writing")
risky()
print("never printed")
except e:
print("caught:", e)

Output:

<log>
writing
</log>
caught: disk full

The tag is closed before the except block sees the error. If you call something that can raise inside with, the usual rules apply: the function needs raises or a try around it, as you’ll see in Try/Except.

You can open more than one in a single with, separated by commas. They’re exited in the reverse order:

@fieldwise_init
struct Tag:
var name: String
def __enter__(self):
print("<" + self.name + ">")
def __exit__(self):
print("</" + self.name + ">")
def main():
with Tag("html"), Tag("body"):
print("hello")

Output:

<html>
<body>
hello
</body>
</html>

Reverse order is what you want for cleanup: the last thing you set up is the first thing you take down. A common real use is copying one file into another: with open("in.txt", "r") as src, open("out.txt", "w") as dst:.

You can write a second __exit__ that takes the error. Mojo calls it instead of the plain one when the block raises an Error. It returns a Bool:

  • True: the error is handled. It stops here, and the code after the with runs.
  • False: the error keeps going, as if __exit__ weren’t there.

Here’s a database-style transaction that commits when everything went well and rolls back when something failed:

@fieldwise_init
struct Transaction:
var name: String
def __enter__(self):
print("begin", self.name)
def __exit__(self):
print("commit", self.name)
def __exit__(self, e: Error) -> Bool:
print("rollback", self.name, "because:", e)
return False
def transfer(amount: Int) raises:
with Transaction("transfer"):
if amount > 100:
raise Error("limit is 100")
print("moving", amount)
def main():
try:
transfer(50)
transfer(500)
except e:
print("failed:", e)

Output:

begin transfer
moving 50
commit transfer
begin transfer
rollback transfer because: limit is 100
failed: limit is 100

Notice that when there’s an error, only the error version runs; you don’t get “commit” as well. If both versions need the same cleanup, call self.__exit__() from the error version. Returning False passes the error on, so the caller still sees it and prints “failed”. The Mojo manual’s section on custom context managers also shows how to handle custom error types in __exit__.

Python Mojo
Use one with open(p) as f: Same
Several at once with a, b: Same
Setup __enter__(self) Same
Cleanup __exit__(self, exc_type, exc, tb) __exit__(self), plus an optional __exit__(self, e: Error) -> Bool
__exit__ optional No Yes, if nothing needs cleaning up
@contextmanager decorator In contextlib Not available; write a struct

Other context managers in the standard library include temporary files and folders in std.tempfile and assert_raises in std.testing.

Write a context manager Banner that prints a line of = (20 of them) before and after the block. Use it to print Results and All tests passed.

Hint: "=" * 20 builds the line. Print it in both __enter__ and __exit__.

Show solution
@fieldwise_init
struct Banner:
def __enter__(self):
print("=" * 20)
def __exit__(self):
print("=" * 20)
def main():
with Banner():
print("Results")
print("All tests passed")

Output:

====================
Results
All tests passed
====================

Banner has no fields, so Banner() takes no arguments. @fieldwise_init still gives it an initializer.

Write a context manager IgnoreMissing that handles errors whose message starts with "missing" and lets all others through. Use it around a call that raises Error("missing file"), and print still running after the with block.

Hint: write __exit__(self, e: Error) -> Bool and check String(e).startswith("missing").

Show solution
@fieldwise_init
struct IgnoreMissing:
def __enter__(self):
pass
def __exit__(self):
pass
def __exit__(self, e: Error) -> Bool:
if String(e).startswith("missing"):
print("ignored:", e)
return True
return False
def load() raises:
raise Error("missing file")
def main() raises:
with IgnoreMissing():
load()
print("still running")

Output:

ignored: missing file
still running

Returning True stops the error, so the program goes on to still running. Any other message would return False and the error would reach main, which is marked raises.

  • with x: calls __enter__ at the start of the block and __exit__ at the end.
  • __exit__ runs no matter how the block ends: normally, with return, break, continue, or an error.
  • as name gets whatever __enter__ returns. __exit__ is optional when there’s nothing to clean up.
  • with open(...) as f: closes the file for you.
  • Several managers in one with are exited in reverse order.
  • An extra __exit__(self, e: Error) -> Bool runs instead on errors: return True to handle the error, False to pass it on.

Next up: value semantics, what really happens when you assign or pass a value, and why Mojo copies where Python shares.

Quick check

1. When does __exit__ run?
2. In with Indent(2) as pad:, what is pad?
3. Your __exit__(self, e: Error) -> Bool returns False. What happens to the error?
4. In with Tag("html"), Tag("body"):, which closing tag is printed first?