Provides a context manager that allows the user to specify a method on the passed-in object to be called when the 'with' statement is exited. This is a generalization of contextlib.closing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | from contextlib import contextmanager
@contextmanager
def call_on_exit(obj, call, *args, **kwargs):
"""Get the attribute 'call' from 'obj' and call with the remaining
arguments upon exiting the context manager.
Upon entrance 'obj' is returned.
"""
try:
yield obj
finally:
fxn = getattr(obj, call)
fxn(*args, **kwargs)
|
Some objects have the general need of a specific method that needs to be called when you are finished using it. Context managers provide a perfect solution for this. So perfect, in fact, that the contextlib module introduced in Python 2.5 has the 'closing' function for calling the 'close' method on the argument to the contextlib.
But this is not general. In wxPython, for instance, some objects need the Destroy method called when you are done using it. This implementation can also easily handling the functionality contextlib.closing provides.
The implementation could have just taken a callable object for its argument to call later. This would have performed better by skipping the need for getattr. Unfortunately that does not provide the handy ability to have the context manager return the object that contains the method at entry.