liveBook · Manning

Context manager protocol

As explained in Python Workout: 50 ten-minute exercises

The context manager protocol is the Python protocol defined by an object's __enter__ and __exit__ methods for managing a with statement's context.

The context manager protocol lets an object control what happens around a with statement. Python calls __enter__ when the context begins and __exit__ when the block ends, giving the object a chance to restore its state. section 5.10

Managing a file

with open('myfile.txt', 'w') as f:\n f.write('abc\n')\n f.write('def\n')\n\nFor files, __exit__ handles important cleanup, including flushing and closing the file. This keeps resource management attached to the block that uses the resource. section 5.10

Use the same protocol for other bounded operations:

  • Pass multiple objects to with; Python invokes their __enter__ and __exit__ methods in turn. section 5.10
  • Define __enter__ and __exit__ on your own classes when they need to behave inside a with statement. section 5.10
  • Apply it to database transactions or locked sections of multithreaded code. section 5.10

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains __enter__ and __exit__, cleanup, multiple objects, and custom classes without detailing method signatures.
Examples
Uses a file-writing block and mentions database transactions, locked sections, multiple objects, and custom context-manager classes.
What you can do after
Apply it via Python's with statement to close files and structure transactional or locking contexts.
How it connects
Connects with statements to file handling, database transactions, and multithreaded locking.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.