Defer in Python

Our first program demonstrates the use of with statement, which is Python’s equivalent to the defer keyword. The with statement ensures that a resource is properly closed or cleaned up when we’re done using it. This is often used for file operations, network connections, or other resources that need to be managed.

import os

def main():
    # Immediately after opening the file with the `with` statement,
    # we ensure that the file will be closed when we're done.
    # This will be executed at the end of the `with` block,
    # after we've finished writing to the file.
    with open("/tmp/defer.txt", "w") as f:
        write_file(f)

def write_file(f):
    print("writing")
    f.write("data\n")

if __name__ == "__main__":
    main()

In this example, we’re creating a file, writing to it, and ensuring it’s properly closed afterwards. The with statement takes care of closing the file for us, even if an exception occurs during the write operation.

Let’s break down the code:

def main():
    with open("/tmp/defer.txt", "w") as f:
        write_file(f)

Here, we’re using the with statement to open a file. This ensures that the file will be properly closed when we exit the with block, regardless of whether an exception occurs or not. It’s equivalent to using try/finally or defer in other languages.

def write_file(f):
    print("writing")
    f.write("data\n")

This function writes some data to the file. Note that we don’t need to explicitly close the file - the with statement takes care of that for us.

Running the program confirms that the file is written to:

$ python defer.py
writing

In Python, we don’t need to explicitly check for errors when closing a file when using the with statement, as it handles this for us. If an error occurs during the file operations, it will be raised as an exception.

This approach using the with statement is considered a Pythonic way to handle resources that need cleanup. It’s concise, readable, and ensures that resources are properly managed.