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
