Meta decorator with parameters, defined in explicit functions

Ian Kelly ian.g.kelly at gmail.com
Sat Jul 2 01:53:15 EDT 2016


On Fri, Jul 1, 2016 at 11:32 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Ian Kelly <ian.g.kelly at gmail.com> writes:
>
>> You should use functools.wraps instead of clobbering the decorated
>> function's name and docstring:
>>
>>         @functools.wraps(decorator)
>>         def decorate(*args, **kwargs):
>>             ...
>
> Thanks. Can you write the full implementation with that, so I can be
> sure of where you expect that to go?

    def decorator_with_args(decorator):
        """Given function decorator(func, *args, **kwargs), returns a
        wrapper that accepts args and kwargs separately from func.
        """
        @functools.wraps(decorator)
        def apply(*args, **kwargs):
            # inner_decorator is transient, so its name and docstring
            # are unimportant.
            def inner_decorator(func):
                return decorator(func, *args, **kwargs)
            return inner_decorator
        return apply



More information about the Python-list mailing list