December 17, 2018

A Simple Pythonic Context Manager

  —A context manager exploiting Python's _with_ statement.

I recently came across the question How do I “cd” in Python? on Stack Overflow. It provides an easy to understand example and use case for writing code that leverage’s Python’s with statement.

Python’s with statement is defined in PEP 343 – The “with” Statement. It introduces two methods __enter__() and __exit__() that are invoked upon entry and exit of the with statement. PEP 343 was written in 2005.

If you haven’t read PEP 343 the discussion on the semantics of with is worth your time.

Other resources:

comments powered by Disqus