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 Playground

Tags

languagesyntaxcorecontext-managerresource-management

Related Items