with — Easy Examples
Wraps a block with a context manager for automatic setup/teardown
Context managers basics
Using 'with' for automatic cleanup.
python
# with ensures cleanup happens even if errors occur class ManagedFile: def __init__(self, name): self.name = name def __enter__(self): print(f"Opening {self.name}") return self def __exit__(self, exc_type, exc_val, exc_tb): print(f"Closing {self.name}") return False with ManagedFile("data.txt") as f: print(f"Working with {f.name}") print("File is now closed")
Expected Output
Opening data.txt Working with data.txt Closing data.txt File is now closed
'with' calls __enter__ at the start and __exit__ at the end, guaranteeing cleanup even if exceptions occur.
Want to try these examples interactively?
Open Easy Playground