with
KeywordPython 2.6+Beginner
Wraps a block with a context manager for automatic setup/teardown
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.6+
Learn by Difficulty
Quick Example
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")
'with' calls __enter__ at the start and __exit__ at the end, guaranteeing cleanup even if exceptions occur.
Try in PlaygroundTags
languagesyntaxcorecontext-managerresource-management
Related Items
as
Keyword
Creates an alias (used with import, with, except)
__enter__
Dunder Method
Called at the start of a with block; returns the context resource
__exit__
Dunder Method
Called at the end of a with block; handles cleanup and exceptions
contextlib
Stdlib — Misc
Context manager utilities: @contextmanager, suppress, ExitStack
open()
Built-in Function
Opens a file and returns a file object for reading or writing