Context Managers
Lesson 1 of 1
  1. 1
    When we use a computer, we tend to interact with its various resources. Similar to how we need to manage resources in our daily lives like our time and energy, resources on a computer also need to…
  2. 2
    One of the most common ways to manage resources in Python is to make sure the files we use in our scripts are properly closed after use. We already explored this concept when we used the with sta…
  3. 3
    Now that we have an understanding of why we need context managers and the power of the with statement, it is essential for us to know what’s happening under the hood to gain a much deeper understan…
  4. 4
    Now that we know the structure of implementing our own class-based context manager. Let’s walk through a context manager that manages actual files as well as explore each of the methods we saw earl…
  5. 5
    Remember this? def exit(self, *exc): It’s time to address the big mystery. What in the world is the *exc parameter in the exit method we have been writing so far? Well, context manager…
  6. 6
    Printing exceptions isn’t the only way we can handle them in the exit method. An exception that occurs in a context manager can be handled in two ways: - If we want to throw an error when an …
  7. 7
    We’ve learned that we can create our own context managers using the class-based method, but there’s an even simpler way of creating context managers. We can use a built-in Python module called cont…
  8. 8
    In the previous exercise, we explored how to create a context manager using the contextlib module. However, we did not go over how to deal with errors just as we did with the class-based approach. …
  9. 9
    So far, we’ve only been using context managers within the context (Ha! Get it?) of one file. In most programs, there might be a need to use context managers for a couple of different scenarios that…
  10. 10
    Congratulations! We have reached the end of the context managers lesson. Making it this far means that we have explored many of the core concepts behind context managers. Let’s recap: **Context M…

What you'll create

Portfolio projects that showcase your new skills

Pro Logo

How you'll master it

Stress-test your knowledge with quizzes that help commit syntax to memory

Pro Logo