Python Context Managers and the "with" Statement

Dan Bader
Dan Bader 6 Lessons 12m intermediate python

Python’s with statement is powered by a language feature called context managers. It helps you simplify some common resource management patterns by abstracting their functionality and allowing them to be factored out and reused.

In this course you’ll learn how context managers and the with statement work in Python, including the difference between class-based and function-based context managers, as well as some other tricks that will make you a more efficient Python developer.

What’s Included:

About Dan Bader

Dan Bader is the owner and editor in chief of Real Python and the main developer of the realpython.com learning platform. Dan has been writing code for more than 20 years and holds a master's degree in computer science.

» More about Dan

Each tutorial at Real Python is created by a team of developers so that it meets our high quality standards. The team members who worked on this tutorial are:

Participant Comments

Avatar image for mikesult

mikesult on March 3, 2020

Nice to get an understanding of the context manager protocol and how some of the dunder methods work. Thank you for another great tutorial.

Avatar image for Tim Pozza

Tim Pozza on May 12, 2019

Detailing the various approaches in context really helps to understand the concept and how one might arrive at an implementation with respect to their own, or a community’s coding knowledge. The possible trouble of using an obscure approach since having its roots revealed is avoided by the awareness of what’s going on and how those who don’t know might get lost in an implementation that’s too far removed syntactically from the underlying logic. Without these videos even saying that would be impossible. Thanks for yet another insight.

Avatar image for ashokbayana369

ashokbayana369 on May 7, 2019

Nice explanation of Context Managers..:)

← Browse All Courses