[Python-Dev] Proposed tweaks to functools.wraps
Steve Holden
steve at holdenweb.com
Wed Aug 11 05:22:34 CEST 2010
On 8/10/2010 10:58 PM, Nick Coghlan wrote:
> On Wed, Aug 11, 2010 at 12:48 PM, Éric Araujo <merwok at netwok.org> wrote:
>>> The second (#9396) came up in the context of the new cache decorators
>>> added to functools, and allowing applications to choose their own
>>> caching strategies. I suggested exposing the original (uncached)
>>> function, and Raymond suggested that the easiest way to enable that
>>> would be for functools.update_wrapper to add a new attribute that
>>> provides a reference to the original function.
>>
>> I moved this feature request to its own bug after brief IRC discussion
>> with RDM: http://bugs.python.org/issue9567
>>
>> The idea was to separate concerns and eventually get feedback from
>> people reading new-bugs-announce, but your email actually does that :)
>>
>> I say “add attribute to partial objects” in the bug title since I don’t
>> know if it’s feasible in wraps only; while update_wrapper is simple
>> Python code, wraps merely delegates to _functools.partial, so please
>> change the title (and maybe add easy keyword) if appropriate.
>
> Ah, that's the trick though - the partial object is the *decorator*,
> so when you write
>
> @wraps(f)
> def wrapper:
> # ....
>
> it is equivalent to:
>
> def wrapper:
> # ....
>
> wrapper = partial(update_wrapper, wrapped=f)(wrapper)
>
> The partial object is a transient thing during the decoration process
> - the wrapper function itself is the object that persists.
>
> So it's only update_wrapper that needs changing to add the new attribute.
>
One of the things that's slightly irking about the decorator syntax is
that a decorator is always called with exactly one argument, and that if
you want to write a parameterized decorator you therefore end up writing
a function that returns a function that returns a function.
I've scratched my head about how partials (or indeed anything else)
could be used to make the extra level of indirection necessary, but
haven' come up with anything that even I could regard as acceptable. But
I can't escape this feeling that there must be a way.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
DjangoCon US September 7-9, 2010 http://djangocon.us/
See Python Video! http://python.mirocommunity.org/
Holden Web LLC http://www.holdenweb.com/
More information about the Python-Dev
mailing list