I love the decorator in Python!!!
Ethan Furman
ethan at stoneleaf.us
Thu Dec 8 18:34:13 EST 2011
Chris Angelico wrote:
> One piece of sophistication that I would rather like to see, but don't
> know how to do. Instead of *args,**kwargs, is it possible to somehow
> copy in the function's actual signature? I was testing this out in
> IDLE, and the fly help for the function no longer gave useful info
> about its argument list.
If you want to roll your own, it looks something like this:
2.x code
----------------------------------------------------------------------
def trace(func, debugmode=debugmode):
if debugmode:
name = func.__name__
argspec = inspect.getargspec(func)
signature = inspect.formatargspec(
formatvalue=lambda val: "", *argspec)[1:-1] # trim parens
new_func = (
'def _wrapper_(%(signature)s):\n'
' print(">"+func.__name__)\n'
' result = func(%(signature)s)\n'
' print("<"+func.__name__)\n'
' return result\n'
% {'signature':signature}
)
evaldict = {'func':func}
exec new_func in evaldict
wrapped = evaldict['_wrapper_']
wrapped.__name__ = name
wrapped.__doc__ = func.__doc__
wrapped.__module__ = func.__module__
wrapped.__dict__ = func.__dict__
wrapped.func_defaults = func.func_defaults
return wrapped
return func
----------------------------------------------------------------------
The downside (which you get even with Michele's decorator module) is
that tracebacks aren't quite as clean.
~Ethan~
More information about the Python-list
mailing list