Context Managers and Using Python's with Statement

The with statement in Python is a quite useful tool for properly managing external resources in your programs. It allows you to take advantage of existing context managers to automatically handle the setup and teardown phases whenever you’re dealing with external resources or with operations that require those phases.

What’s a context manager? It’s a block of code that has side effects upon entering and exiting. The context management protocol allows you to create your own context managers so you can customize the way you deal with system resources.

In this video course, you’ll learn:

  • How context managers work
  • Some common context managers in the Python standard library
  • How to write a custom context manager

With this knowledge, you’ll write more expressive code and avoid resource leaks in your programs.

What’s Included:

  • 8 Lessons
  • Video Subtitles and Full Transcripts
  • 2 Downloadable Resources
  • Accompanying Text-Based Tutorial
  • Interactive Quiz to Check Your Progress
  • Q&A With Python Experts: Ask a Question
  • Certificate of Completion

Downloadable Resources:

Related Learning Paths:

Common Usage in the Standard Library

2 Lessons 10m

  1. 1. Files and Directories04:48
  2. 2. Precision and Threading Locks05:22

About Christopher Trudeau

Christopher has a passion for the Python language and writes for Real Python. He is a consultant who helps advise organizations on how to improve their technical teams.

» More about Christopher

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:

← Browse All Courses