Custom Context Manager
Custom Context Manager is a reusable Python snippet. Create your own context managers using the `with` statement for resource management. The full implementation: # Using __enter__ and __exit__ class ManagedFile: def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename, "w") return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() with ManagedFile("test.txt") as f: f.write("Hello!") # Using contextlib.contextmanager from contextlib import contextmanager @contextmanager def managed_file(filename): f = open(filename, "w") try: yield f finally: f.close() with managed_file("test.txt") as f: f.write("Hello again!") It belongs to the Built-in Functions area of the standard library. This snippet uses only the Python standard library with no third-party dependencies, so it runs on any modern Python 3 interpreter. Browse more patterns in the snippet library, or paste the code straight into the playground to experiment with it.