liveBook · Manning

__enter__ method

As explained in Python Workout: 50 ten-minute exercises

The __enter__ method is a special Python method invoked when execution enters a context manager and whose return value is bound by the with statement.

When a with statement begins, Python checks the managed object for __enter__ and runs it. The method’s return value becomes the object named after as. For files, __enter__ returns the file object itself, while cleanup happens through __exit__ when the block ends. section 5.10

Track the entry sequence:

File entry in practice

with open('myfile.txt', 'w') as f: f.write('abc\n') f.write('def\n') Here, __enter__ supplies the file object bound to f; __exit__ flushes and closes it after the block. section 5.10

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Explains invocation and return-value binding, but stops before custom context-manager implementation details.
Examples
Uses open with file writing to show return-value binding and automatic flushing and closing.
What you can do after
Evaluate how a with statement obtains and binds its managed object before executing the block.
How it connects
Connects __enter__ method to context managers, the with statement, files, and __exit__ method.

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.