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

Ian Kelly ian.g.kelly at gmail.com
Sat Jun 11 16:28:27 EDT 2011


On Sat, Jun 11, 2011 at 1:27 PM, Giampaolo Rodolà <g.rodola at gmail.com> wrote:
>    @deprecated()
>    def foo():
>        return 0

This is equivalent to:

foo = deprecated()(foo)

>    @deprecated(some_function)
>    def foo():
>        return 0

foo = deprecated(some_function)(foo)

>    @deprecated
>    def foo():
>        return 0

foo = deprecated(foo)

You want to make the third case be equivalent to the first case.  The
problem is that there is no way to distinguish between
"deprecated(foo)" (in the third case) and "deprecated(some_function)"
in the second case.  Both are receiving a single argument that is a
function, but the latter needs to return a decorator while the former
needs to return a decorated function.

Since there is no way to distinguish the two cases by the arguments,
you would need a separate decorator.  You could do something like
this:

deprecated_default = deprecated()

@deprecated_default
def foo():
    return 0

But this hardly seems worthwhile to me just to avoid typing an extra
couple of parentheses.

Cheers,
Ian



More information about the Python-list mailing list