[Python-Dev] Adding functools.decorator

Georg Brandl g.brandl at gmx.net
Sun Apr 30 17:23:53 CEST 2006


Nick Coghlan wrote:
> Collin Winters has done the work necessary to rename PEP 309's functional 
> module to functools and posted the details to SF [1].
> 
> I'd like to take that patch, tweak it so the C module is built as _functools 
> rather than functools, and then add a functools.py consisting of:

I'm all for it. (You could integrate the C version of "decorator" from my SF
patch, but I think Python-only is enough).

> from _functools import * # Pick up functools.partial
> 
> def _update_wrapper(decorated, func, deco_func):
>      # Support naive introspection
>      decorated.__module__ = func.__module__
>      decorated.__name__ = func.__name__
>      decorated.__doc__ = func.__doc__
>      decorated.__dict__.update(func.__dict__)
>      # Provide access to decorator and original function
>      decorated.__decorator__ = deco_func
>      decorated.__decorates__ = func
> 
> def decorator(deco_func):
>      """Wrap a function as an introspection friendly decorator function"""
>      def wrapper(func):
>          decorated = deco_func(func)
>          if decorated is func:
>              return func
>          _update_wrapper(decorated, func, deco_func)
>          return decorated
>      # Manually make this decorator introspection friendly
>      _update_wrapper(wrapper, deco_func, decorator)
>      return wrapper
> 
> After typing those four lines of boilerplate to support naive introspection 
> out in full several times for contextlib related decorators, I can testify 
> that doing it by hand gets old really fast :)

Agreed.

Georg



More information about the Python-Dev mailing list