Snake_Byte #25: Taken Out of Context

Context is important. It's why nursery rhymes make your hair stand on end in horror films but not when you sing them to children to help them sleep. For the purpose of Python programming, let's talk about a special object type called context managers. One of the most common usages is the canonical way to open and interact with a file in Python:

Behind the scenes, Python is opening a new file descriptor named input for read operations and, after leaving the context of the indented block, the file descriptor is quietly closed to free up that system level handle for reuse. Nice, right? Context managers are great for frequently repeated tasks that have overhead such as cleanup, variable tracking, or sending a message. An example of a simpler custom context manager:

With this we can check the "wall clock" execution time of arbitrary blocks of code such as:

This produces output like:

Notice that the output from the __enter__ and __exit__ functions appears before and after the indented block code respectively, as you enter and exit the context of the indented block. The __exit__ method can even be used to handle exceptions and restore working state if something goes wrong in the indented block. So when it comes to Python, it's OK to be taken out of context.

About anthonyadkins

Making the possibly impossible impossibly possible

View All Posts