Meta decorator with parameters, defined in explicit functions

Ian Kelly ian.g.kelly at gmail.com
Sun Jul 3 07:52:47 EDT 2016


On Sat, Jul 2, 2016 at 11:37 PM, Lawrence D’Oliveiro
<lawrencedo99 at gmail.com> wrote:
> On Sunday, July 3, 2016 at 4:49:15 PM UTC+12, Ian wrote:
>>
>> On Sat, Jul 2, 2016 at 12:40 AM, Lawrence D’Oliveiro wrote:
>>>
>>> On Saturday, July 2, 2016 at 5:10:06 PM UTC+12, Ian wrote:
>>>>
>>>> You should use functools.wraps instead of clobbering the decorated
>>>> function's name and docstring:
>>>
>>> Where am I doing that?
>>
>> Using the implementation you posted:
>>
>>>>> @decorator_with_args
>> ... def my_decorator(func, *args, **kwargs):
>> ...     """Returns func unmodified."""
>> ...     return func
>> ...
>>>>> my_decorator.__doc__
>> 'generates a decorator which applies my_decorator to the given arguments'
>
> That is a function that I am generating, so naturally I want to give it a useful docstring. Am I “clobbering” any objects passed in by the caller, or returned by the caller? No, I am not.

It isn't useful, though. If somebody writes a docstring for a
function, it's because they want that to be the docstring for the
function, not some arbitrary and vague docstring assigned by a
decorator. If I type "help(my_decorator)" in the interactive
interpreter, I should see what my_decorator actually does, not
"generates a decorator which applies my_decorator", which just
confuses with its recursiveness. The only way to find out what
my_decorator actually does from the interactive interpreter would be
to realize that it's been opaquely decorated and type out something
like this:

>>> my_decorator.__closure__[0].cell_contents.__doc__
'Returns func unmodified.'

That's far too obscure. Alternatively, one could go read the source.
But if you have to go read the source to understand what a function
does, then you've lost the purpose of having a docstring in the first
place.



More information about the Python-list mailing list