Context Managers

In the previous lesson, we learned best practices for writing functions in Python. To further our knowledge of Python functions advanced techniques, we'll learn how to use and write context managers, a type of function that sets up a context for your code to run in, runs your code, and then removes the context.

In this lesson, we'll learn what context managers are, their role in functions, as well as why they're important. While you may have used a Python context manager before, you may not have known they're called that. This lesson will help you will build your intuition for context managers and when it's a good time to use them in your code. 

By the end of the lesson, you'll be able to decipher when is a good opportunity to use a context manager, and when it might not be a good idea. You will have also learned how to write your own Python context managers using a decorator, an advanced Python concept that we will cover in the next module.

As you learn about Python context managers and how to use them, you’ll get to apply what you’ve learned from within your browser so that there's no need to use your own machine to do the exercises. The Python environment inside of this course includes answer checking so you can ensure that you've fully mastered each concept before learning the next concept.


  • Learn how to use context managers.
  • Learn how to write your own context managers.

Mission Outline

1. Introduction
2. Using Context Managers
3. Using Context Managers Continued
4. Writing Context Managers
5. Writing Context Managers Continued
6. Nested Contexts
7. Handling Errors
8. When to Create Context Managers
9. Next steps
10. Takeaways

Course Info:


The median completion time for this course is 6 hours. View Details

This course requires a premium subscription. This course includes four missions.  It is the 27th course in the Data Scientist in Python path.


Take a Look Inside

(function(d) { d.addEventListener("DOMContentLoaded", function() { var pathname = d.location.pathname.replace(/^[/]|[/]$/g, "").replace("/", "-"); var tags = d.getElementsByTagName("iframe"); var type = pathname.startsWith("course") ? "?course=" : pathname.startsWith("path") ? "?path=" : null; if (type) { var i; for (i = 0; i < tags.length; i++) { if (tags[i].src.indexOf("signup#iframe") !== -1) { tags[i].src = tags[i].src.replace("#iframe", "") + type + pathname + "#iframe"; } } } }, false); })(document);