I have a number of calls I need to make to functions imported from a package (the package is a shared object file). However I need to do some pre-process / post – process step every time I make a call to a function from this package. Something like this:
import xyz
prepare()
xyz.foo(<args>)
done()
prepare()
xyz.bar(<args>)
done()
prepare()
xyz.foobar()
done()
Is there some way I can ask python to always invoke prepare() before I call a function from xyz module. And also to invoke done() after the call is complete?
Writing prepare and done through my whole code seems redundant and messy. Appreciate your help!
>Solution :
This is typically done with a context manager.
import contextlib
@contextlib.contextmanager
def with_preparation():
prepare()
yield
done()
with preparation():
xyz.foo(<args>)
with preparation():
xyz.bar(<args>)
with preparation():
xyz.foobar()
preparation defines a function that returns a context manager. The with statement works by invoking the context manager’s __enter__ method, then executing the body, then ensuring that the context manager’s __exit__ method is invoked before moving on (whether due to an exception being raised or the body completing normally).
contextlib.contextmanager provides a simple way to define a context manager using a generator function, rather than making you define a class with explicit __enter__ and __exit__ methods.