[Python-Dev] Proposed tweaks to functools.wraps

Simon Cross hodgestar+pythondev at gmail.com
Wed Aug 11 16:12:11 CEST 2010


On Wed, Aug 11, 2010 at 3:00 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>> * The decorator returns the original function (I suppose a reference
>> to itself is okay?)
>
> There's no reason why a function can't have an attribute that refers to
> the function itself. It works fine:

Yes. But it's more common for the original function to have be
modified in some way. e.g.:

def autodoc(f):
    f.__doc__ += document_args(f)
    return f

@autodoc
def f(x, y):
     """Add two numbers"""
     return x + y

And then f.__wrapped__ is not particularly useful because the original
function no longer exists and odd things will happen. For example, in
the code above autodoc(f.__wrapped__).__doc__ will not equal
f.__doc__.

>> * The decorator returns the a function that is already decorating
>> something else.
>
> That shouldn't make any difference. Given:
>
> @wraps(f)
> def func(*args):
>    do_something()
>    return f(*args)
>
> then func.__wrapped__ gives f. If f itself wraps (say) g, and g wraps h,
> then you have:

I guess my description of the problem wasn't clear. I meant:

def _debug(*args, **kwargs)
    print args, kwargs

def mock(f):
    return _debug

@mock
def plus(a, b):
   return a + b

@mock
def prod(a, b):
    return a * b

Schiavo
Simon


More information about the Python-Dev mailing list