Python Context Manager
summary
Recently used this, carefully understand a little, feel that is very useful, record it
Usage Scenarios
When we need to fetch a temporarily opened resource and perform resource release and exception handling after use, utilizing a try-catch statement can be done, as an example.
Open the file:
f = None try: print("try") f = open("__init__.py", "r") print(()) except Exception as e: print("exception") finally: if f: print("finally") ()
Utilize the context manager:
class OpenHandle: def __init__(self, filename, mode): = filename = mode def __enter__(self): = open(, ) return def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: print("exception") else: print("normal") () with OpenHandle("", "r") as f: print(())
This allows you to rewrite the code using the with-as statement, allowing the programmer to focus on the main business process, removing the repetitive operations of acquiring and closing resources. Improve code readability. The benefits are great.
order of execution
The order of execution is key to understanding this writing style:
- Initialize, execute handle's __init__()
- __enter__() method, get the resource object, return to the variable after as
- Business Code Logic
- __exit__ method, pass 3 parameters, exception type, exception object, call stack object, no exception are None
- Throw an exception or end normally
Functional Context Manager
Using the decorator from contextlib import contextmanager you can decorate a function as a context manager, in fact behind this decoration also returns a class that implements the __enter__ and __exit__ methods
from contextlib import contextmanager @contextmanager def managed_resource(*args, **kwds): # Code to acquire resource, .: resource = acquire_resource(*args, **kwds) try: yield resource finally: # Code to release resource, .: release_resource(resource) >>> with managed_resource(timeout=3600) as resource: ... # Resource is released at the end of this block, ... # even if code in the block raises an exception
Template Code
sqlalchemy session context manager
This is perfect for managing the acquisition and release of sqlalchemy session objects and controlling transactions.
class DbTransaction: def __init__(self, session_maker): self.session_maker = session_maker def __enter__(self): = self.session_maker() return def __exit__(self, exc_type, exc_val, exc_tb): if exc_type: () else: () () return False if exc_type else True
These are all the relevant points, thanks for learning and supporting me.