Capturing invoking method information in Python
The following decorator will capture all available information regarding the method which invokes the decorated method (the invoked method).
The available information consists of the following:
- a) the instance object of the invoker (the subject),
- b) the name of the method (the name), and
- c) the invocation frame in the current stack (the frame).
This information is passed to the invoked method through a keyword argument, by default
_invoker_info, which can be overridden through the
name argument to the decorator.
The following example demonstrates its use. Assume a class
A which defines two methods,
y is decorated with the above decorator:
An instance object
b of class
B will return the following captured information tuple when its
x method is invoked:
>>> b.x() (<__main__.B object at 0x10162ee90>, 'x', <frame object at 0x101560090>)
And, since we are in the interactive Python shell, the same object
b will return the following captured information tuple when its
y method is invoked:
>>> b.y() (None, '<module>', <frame object at 0x101562750>)
Predictably, the subject here is
None, as the invocation was performed from the shell and not another instance object.