What does `contextlib.contextmanager` allow and how does `yield` work inside it?

Python Developer Hard

Python Developer — Hard

What does `contextlib.contextmanager` allow and how does `yield` work inside it?

Key points

  • `contextlib.contextmanager` enables creating context managers with generator functions
  • `yield` separates __enter__ and __exit__ code
  • Exceptions from the with block are handled at the yield point

Ready to go further?

Related questions