Python context manager magic

n1
n1
Sep 3, 2018 · 1 min read

I guess you already know the magic behind with keyword. If not you can fix it right here. In short with is a statement which has an enter and an exit. On both you can perform actions. It usually happends in a custom class where you place __enter__() and __exit__() methods. But there is another solution which you can take advantage of. It’s called contextmanager decorator.

Output is:

In the example above we have class X which we instantiate and run it’s y() method. The method prints “before” then yields back to the parent (which is our with statement) a variable x, where we print it and when the with statement is over it jumps back to y() method right where it left of — after yield keyword. The method y() finishes normally — “after” is printed.

So we can see that contextmanager decorator can be used on a function or on a class method. We also see the life cycle:

  1. we spawn the context manager from caller by with keyword
  2. context manager runs
  3. once it hits yield keyword it returns back to the caller with a variable
  4. caller continues to run
  5. once it ends it’s life (with is done) jump back to y() to finish itself
  6. y() is done
n1

Written by

Python and stuff

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade