def foo(a, b, c = 0):
return a+b
I have dozens of functions like "foo" that have different argument numbers and names. Is there a general way to get the return values ββof these functions and perform only one additional operation, such as pformat?
Yes, I can just generate a new function, such as:
func = ...
def wrapper(*arg, **kw):
data = func(*arg, **kw)
return pprint.pformat(data)
return wrapper
But then the new "wrapper" function is different from the old "func", for example, in the argument number, "wrapper" has only 2 arguments - "arg" and "kw", but "func" can have many arguments, such as 'a' , 'b', 'c'.
I just want to play with the return value, everything else should remain in place, is this possible?
Thank!
, decorator :
--- /home/jaime/cache/decorator-3.2.0/src/decorator.py 2010-05-22 23:53:46.000000000 +0800
+++ decorator.py 2010-10-28 14:55:11.511140589 +0800
@@ -66,9 +66,12 @@
self.name = '_lambda_'
self.doc = func.__doc__
self.module = func.__module__
- if inspect.isfunction(func):
+ if inspect.isfunction(func) or inspect.ismethod(func):
argspec = inspect.getargspec(func)
self.args, self.varargs, self.keywords, self.defaults = argspec
+ if inspect.ismethod(func):
+ self.args = self.args[1:]
+ argspec = inspect.ArgSpec(self.args, self.varargs, self.keywords, self.defaults)
for i, arg in enumerate(self.args):
setattr(self, 'arg%d' % i, arg)
self.signature = inspect.formatargspec(
, "", decorator.decorator , .
:
def __getattr__(self, attr):
def pformat_wrapper(f, *args, **kw):
data = f(*args, **kw)
return pprint.pformat(data, indent = 4)
method = getattr(self.ncapi, attr)
return decorator(pformat_wrapper, method)
jaime@westeros:~/bay/dragon.testing/tests$ python
Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56)
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import decorator
>>> class A:
... def f(self):
... pass
...
>>> a = A()
>>> a.f
<bound method A.f of <__main__.A instance at 0xb774a20c>>
>>> def hello(f, *args, **kw):
... print 'hello'
... return f(*args, **kw)
...
>>> f1 = decorator.decorator(hello, a.f)
>>> f1()
hello
>>>