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:
- Place an object in a with statement. section 5.10
- Run __enter__ when the block starts. section 5.10
- Bind its return value to the as variable. section 5.10
- Run __exit__ when the block ends. section 5.10
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
