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.
with and files
Section titled “with and files”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 linesecond lineopen() 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.
Writing your own context manager
Section titled “Writing your own context manager”A context manager is a struct with two special methods:
__enter__runs when thewithblock starts.__exit__runs when the block ends.
Here’s one that prints a header and a footer around some output:
@fieldwise_initstruct 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: reportline 1line 2--- end: reportafter the blockSection("report") creates the struct, with calls its __enter__, then runs the block, then calls __exit__. The struct is thrown away right after that.
What as gives you
Section titled “What as gives you”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_initstruct 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 teaIndent 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.
__exit__ always runs
Section titled “__exit__ always runs”The whole point of __exit__ is that it runs however the block ends. That includes continue, break and return:
@fieldwise_initstruct 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>8When 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_initstruct 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 fullThe 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.
Several context managers at once
Section titled “Several context managers at once”You can open more than one in a single with, separated by commas. They’re exited in the reverse order:
@fieldwise_initstruct 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:.
Reacting to errors in __exit__
Section titled “Reacting to errors in __exit__”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 thewithruns.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_initstruct 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 transfermoving 50commit transferbegin transferrollback transfer because: limit is 100failed: limit is 100Notice 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__.
Coming from Python
Section titled “Coming from Python”| 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.
Practice
Section titled “Practice”1. A banner
Section titled “1. A banner”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_initstruct Banner: def __enter__(self): print("=" * 20)
def __exit__(self): print("=" * 20)
def main(): with Banner(): print("Results") print("All tests passed")Output:
====================ResultsAll tests passed====================Banner has no fields, so Banner() takes no arguments. @fieldwise_init still gives it an initializer.
2. Ignore a known error
Section titled “2. Ignore a known error”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_initstruct 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 filestill runningReturning 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, withreturn,break,continue, or an error.as namegets 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
withare exited in reverse order. - An extra
__exit__(self, e: Error) -> Boolruns instead on errors: returnTrueto handle the error,Falseto 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Use a context manager: the manual’s explanation of
with, with file examples. - Write a custom context manager:
__enter__,__exit__, conditional exits and typed errors. FileHandle: the file type thatopen()returns, and its methods.- Python’s
withstatement: how the Python version works, if you want to compare.