[Python-Dev] Adding functools.decorator
Nick Coghlan
ncoghlan at iinet.net.au
Sun Apr 30 15:56:19 CEST 2006
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:
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 :)
Some details that are up for discussion:
- which of a function's special attributes should be copied/updated?
- should the __decorates__ and __decorator__ attributes be added?
If people are happy with this idea, I can make sure it happens before alpha 3.
Cheers,
Nick.
[1] http://www.python.org/sf/1478788
--
Nick Coghlan | ncoghlan at gmail.com | Brisbane, Australia
---------------------------------------------------------------
http://www.boredomandlaziness.org
More information about the Python-Dev
mailing list