Python context manager magic
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:
- we spawn the context manager from caller by
withkeyword - context manager runs
- once it hits
yieldkeyword it returns back to the caller with a variable - caller continues to run
- once it ends it’s life (
withis done) jump back toy()to finish itself y()is done
