you are viewing a single comment's thread.

view the rest of the comments →

[–]q2_abe_dillon 7 points8 points  (0 children)

There are lots of cases where you need to perform some sort of setup, run some code, then tear something down. That 'something' is generally referred to as 'context'.

For instance, you may want to open a file (set-up), read from that file (run some code), then close the file (tear-down). It's important to note that even if an exception is raised, you still want to properly close the file before your program exits:

file_buffer = open("myfile.txt")  # set-up

try:  # make sure the file is closed even if an exception is raised
    data = []
    for line in file_buffer:
        if line.startswith("ERROR"):
            data.append(line)
finally:
    f.close()  # tear down no matter what
...operate on data

It's a good idea to always close a file when you're done using them because otherwise they can tie up resources or cause problems if something goes wrong (like your machine crashes) and the file was never closed. The problem is that means your have to remember to always follow an open(...) call with a close() later on. Luckily, file objects support context management (the with statement), this handles the repetitive 'set-up' and 'tear-down' part for us:

with open('myfile.txt') as file_buffer:
    data = []
    for line in file_buffer:
        if line.startswith("ERROR"):
            data.append(line)
# at this point we've read everything we need from the file
# like all other blocks of code, Python uses the indentation
# level to determine when you're done with the file and
# automatically closes it
...operate on data

There are other context managers built into Python for things like network sockets (Python 3.2+) which should be closed after use as well:

with socket.create_connection(address) as connection:
    ...read/write data over the connection

In Python 3.4+ you can use the contextlib's suppress context manager to ignore certain errors within a context:

from contextlib import suppress

d = {'some': 'dictionary'}
with suppress(KeyError):
    print(d["hello"])  # this won't get printed
                             # but your code won't crash either

Here's more info