How to avoid "()" when writing a decorator accepting optional arguments?

Ian Kelly ian.g.kelly at gmail.com
Fri Jun 17 09:53:41 EDT 2011


On Fri, Jun 17, 2011 at 4:27 AM, bruno.desthuilliers at gmail.com
<bruno.desthuilliers at gmail.com> wrote:
> On Jun 11, 10:28 pm, Ian Kelly <ian.g.ke... at gmail.com> wrote:
>>
>> Since there is no way to distinguish the two cases by the arguments,
>
> def deprecated(func=None, replacement=None):
>    if replacement:
>       # handle the case where a replacement has been given
>    elif func:
>       # handle the case where no replacement has been given
>    else:
>       raise ValueErrorOrSomethingLikeThis()
>
>
> @deprecated(replacement=other_func):
> def some_func(args):
>    # code here
>
> @deprecated
> def another_func(args):
>    # code here

That works, but I would be concerned about forgetting to specify the
argument by keyword, which would have the effect of deprecating the
replacement function and then calling it on the function that was
intended to be deprecated.  Also, as in my suggestion, it doesn't seem
like a big improvement to have to type out "replacement=" when you
need the replacement function just to avoid typing "()" when you
don't.

Cheers,
Ian



More information about the Python-list mailing list