Using @contextmanager The @contextmanager decorator is an elegant and practical tool that brings together three distinctive Python features: a function decorator, a generator, and the with statement. Using @contextmanager reduces the boilerplate of creating a context manager: instead of writing a whole class with __enter__/__exit__ methods, you just implement a generator with a single yield that should produce whatever you want the __enter__ method to return. In a generator decorated with @contextmanager, yield splits the body of the function in two parts: everything before the yield will be
...more