142 lines
5.4 KiB
Mojo
142 lines
5.4 KiB
Mojo
# Obtain a file handle to read from storage
|
|
var f = open(input_file, "r")
|
|
var content = f.read()
|
|
# Process the content as needed
|
|
# Close the file handle
|
|
f.close()
|
|
```
|
|
|
|
Calling [`close()`](/docs/std/io/file/FileHandle/#close) releases the
|
|
memory and other operating system resources associated with the opened file. If
|
|
your program were to open many files without closing them, you could exhaust the
|
|
resources available to your program and cause errors. The problem is even worse
|
|
if you were writing to a file instead of reading from it, because the operating
|
|
system might buffer the output in memory until the file is closed. If your
|
|
program were to crash instead of exiting normally, that buffered data could be
|
|
lost instead of being written to storage.
|
|
|
|
The example above includes the call to `close()`, but it ignores the
|
|
possibility that [`read()`](/docs/std/io/file/FileHandle/#read) could
|
|
raise an error, which would prevent the `close()` from executing.
|
|
To handle this scenario, you could rewrite the code to use `try` like this:
|
|
|
|
```mojo
|
|
# Obtain a file handle to read from storage
|
|
var f = open(input_file, "r")
|
|
|
|
try:
|
|
var content = f.read()
|
|
# Process the content as needed
|
|
finally:
|
|
# Ensure that the file handle is closed even if read() raises an error
|
|
f.close()
|
|
```
|
|
|
|
However, the [`FileHandle`](/docs/std/io/file/FileHandle/) struct
|
|
returned by [`open()`](/docs/std/io/file/open/) is a context manager.
|
|
When used with Mojo's `with` statement, a context manager ensures that the
|
|
resources it manages are properly released at the end of the block, even if an
|
|
error occurs. In the case of a `FileHandle`, that means the call to `close()`
|
|
takes place automatically. So you could rewrite the example above to take
|
|
advantage of the context manager (and omit the explicit call to `close()`)
|
|
like this:
|
|
|
|
```mojo
|
|
with open(input_file, "r") as f:
|
|
var content = f.read()
|
|
# Process the content as needed
|
|
```
|
|
|
|
The `with` statement also allows you to use multiple context managers within the
|
|
same code block. As an example, the following code opens one text file, reads
|
|
its entire content, converts it to upper case, and then writes the result to a
|
|
different file:
|
|
|
|
```mojo
|
|
with open(input_file, "r") as f_in, open(output_file, "w") as f_out:
|
|
var input_text = f_in.read()
|
|
var output_text = input_text.upper()
|
|
f_out.write(output_text)
|
|
```
|
|
|
|
`FileHandle` is perhaps the most commonly used context manager. Other examples
|
|
of context managers in the Mojo standard library are
|
|
[`NamedTemporaryFile`](/docs/std/tempfile/tempfile/NamedTemporaryFile/),
|
|
[`TemporaryDirectory`](/docs/std/tempfile/tempfile/TemporaryDirectory/),
|
|
[`BlockingScopedLock`](/docs/std/utils/lock/BlockingScopedLock/), and
|
|
[`assert_raises`](/docs/std/testing/testing/assert_raises/). You can also
|
|
create your own custom context managers, as described in [Write a custom context
|
|
manager](#write-a-custom-context-manager) below.
|
|
|
|
## Write a custom context manager
|
|
|
|
Writing a custom context manager is a matter of defining a
|
|
[struct](/docs/manual/structs/) that implements two special *dunder* methods
|
|
("double underscore" methods): `__enter__()` and `__exit__()`:
|
|
|
|
- `__enter__()` is called by the `with` statement to enter the runtime context.
|
|
The `__enter__()` method should initialize any state necessary for the context
|
|
and return the context manager.
|
|
|
|
- `__exit__()` is called when the `with` code block completes execution, even if
|
|
the `with` code block terminates with a call to `continue`, `break`, or
|
|
`return`. The `__exit__()` method should release any resources associated with
|
|
the context. After the `__exit__()` method returns, the context manager is
|
|
destroyed.
|
|
|
|
If the `with` code block raises an error, then the `__exit__()` method runs
|
|
before any error processing occurs (that is, before it is caught by a
|
|
`try`/`except` structure or your program terminates). If you'd like to define
|
|
conditional processing for error conditions in a `with` code block, you can
|
|
implement an overloaded version of `__exit__()` that takes an error
|
|
argument. For more information, see
|
|
[Define a conditional `__exit__()` method](#define-a-conditional-__exit__-method)
|
|
and
|
|
[Handle typed errors in `__exit__()`](#handle-typed-errors-in-__exit__)
|
|
below.
|
|
|
|
For context managers that don't need to release resources or perform other
|
|
actions on termination, you are not required to implement an `__exit__()`
|
|
method. In that case the context manager is destroyed automatically after the
|
|
`with` code block completes execution.
|
|
|
|
Here is an example of implementing a `Timer` context manager, which prints the
|
|
amount of time spent executing the `with` code block:
|
|
|
|
```mojo title="context_mgr.mojo"
|
|
import std.sys
|
|
import std.time
|
|
|
|
@fieldwise_init
|
|
struct Timer(ImplicitlyCopyable):
|
|
var start_time: Int
|
|
|
|
def __init__(out self):
|
|
self.start_time = 0
|
|
|
|
def __enter__(mut self) -> Self:
|
|
self.start_time = Int(time.perf_counter_ns())
|
|
return self
|
|
|
|
def __exit__(mut self):
|
|
var end_time = time.perf_counter_ns()
|
|
var elapsed_time_ms = round(
|
|
Float64(end_time - self.start_time) / 1e6, 3
|
|
)
|
|
print("Elapsed time:", elapsed_time_ms, "milliseconds")
|
|
|
|
def main() raises:
|
|
with Timer():
|
|
print("Beginning execution")
|
|
time.sleep(1.0)
|
|
if len(sys.argv()) > 1:
|
|
raise "simulated error"
|
|
time.sleep(1.0)
|
|
print("Ending execution")
|
|
```
|
|
|
|
Running this example produces output like this:
|
|
|
|
```sh
|
|
mojo context_mgr.mojo
|