Mike Driscoll
Mike Driscoll

@driscollis

8 Tweets 2 reads Dec 20, 2022
#Python has had the concept of context managers for a loooong time!
Let's talk about context managers again!
πŸ§΅πŸπŸ‘‡
The `with` statement, which is the normal way for working with context managers, was added back in Python 2.5!
Here is a pretty common example of using a context manager:
The beauty of a context manager is that they allow you to do some setup and teardown automatically.
The downside is that is abstracted away and can sometimes make the code less obvious when debugging
While there are many things in Python that are built-in context managers, you can also write your own!
All you need to do is create a class and override the following methods:
🐍 __enter__
🐍 __exit__
When you use the `with` statement, it will take the return value from the `__enter__` method. You can assign that to a value or throw it away.
In the following example, you turn `self.conn` into `data`
with DataConn() as data:
pass
When you drop out of the `with` statement's code block, the `__exit__()` method is called.
Here is where you put your cleanup code. You can catch errors here too and handle them as you see fit.
Some devs will log the error and then re-raise it, for example
I also wrote up a thread on using #Python's awesome `contextlib` module which makes creating context managers even easier:
I hope you enjoyed this quick review of #Python context managers.
Follow me for more great content on Python!

Loading suggestions...