What does the following pattern with __enter__ returning self enable? class Resource: def __enter__(self): return self def __exit__(self, *args): self.close() return False def close(self): pass with Resource() as r: print(r is not None)

Python Professional Hard

Python Professional — Hard

What does the following pattern with __enter__ returning self enable? class Resource: def __enter__(self): return self def __exit__(self, *args): self.close() return False def close(self): pass with Resource() as r: print(r is not None)

Key points

  • __enter__ returning self binds the resource to r
  • Enables method calls on r within the with block
  • r refers to the original resource, not a copy
  • __exit__ method is used to clean up resources

Ready to go further?

Related questions