How do I write a Python class that handles calls on undefined methods by first, getting the output of a function of the same name from a given module, and then, doing something further with that output?
For example, given add(x, y), doublerInstance.add(1, 1) should return 4.
I know _ _ getattr _ _() intercepts calls on undefined methods, and getattr() can retrieve a function object. But I don't know how get the arguments passed to the undefined call caught by _ _ getattr _ _() to the function retrieved by getattr().
EXAMPLE
Module functions.py:
def add(x, y):
return x +
Module doubler.py:
class Doubler:
def __init__(self, source):
self.source = source
def __getattr__(self, attrname):
fnc = getattr(self.source, attrname)
return fnc() * 2
Session:
>import functions as f
>import doubler as d
>doublerInstance = d.Doubler(f)
>doublerInstance.add(1, 2)
<snip> TypeError: add() takes exactly 2 arguments, (0 given)
END
I do understand the error -- getattr() returns a function to be run, and the call fnc() doesn't pass any arguments to that function -- here, add(). But how do I get the arguments passed in to the call dblr.add(1, 2) and pass those to the function returned by the getattr() call?
I'm looking for the right way to do this, not some usage of _ _ getattr _ _. I realize that decorator functions using @ might be a better tool here, but I don't yet understand those well enough to see whether they could be applied here.
ALSO -- what resource should I have looked at to figure this out for myself? I haven't found it in the Lutz books, the Cookbook, or the Python Library Reference.