With: Context Managers
Basic concept
with (or with...as...) is actually a special sign that tells the interpreter to call a certain function when entering with block and call another function when leaving with block.
Since it calls a function, it will get return object. We can use
with...as...to catch this object.
Context manager classes
For each class that implements __enter__ and __exit__, it is a context manager.
1 | class CTManager: |
For a context manager class, if it hasn't been initialized, __init__ will be called. Then __enter__ will be implemented automatically and __exit__ will be implemented when leaving the block.
Context manager functions
The definition of context manager functions is much easier than context manager classes since it is almost the same as defining a generator:
1 | import contextlib |
Before creating a context manager function, we should import contextlib and pass the context manager function as a parameter to contextlib.contextmanager.
@has two meanings in python:
- Matrix multiplication
A @ B;- Function modifier: Pass the function defined below it as a parameter of the function behind it.
When with a context manager function, the function will keep running to yield. Then, finish the code left when with block finishs.