Resource Management
Learn to harness the power of context managers in Python!
StartContext Managers
Lesson 1 of 1
- 1When 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…
- 2One 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…
- 3Now 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…
- 4Now 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…
- 5Remember 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…
- 6Printing 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 …
- 7We’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…
- 8In 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. …
- 9So 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…
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory