[Python-ideas] Decorator syntax restriction

Rob Cliffe rob.cliffe at btinternet.com
Sun Sep 6 18:41:33 CEST 2009


Can I make another plea for the syntax following '@' to be an unrestricted expression?  Guido has said he has a 'gut feeling' against this but has not as far as I know rationalised it.

1) It is inconsistent with Python in general (unPythonic) to impose arbitrary restrictions in one particular place, and hard to explain to someone learning the language.

2) The restriction is in any case more apparent than real,
as 
    @ <any-expression> # disallowed, SyntaxError
can be implemented, albeit in a more verbose aka less Pythonic was, as:

    AnyExpr = <any-expression>
    @AnyExpr

or as

    def Identity(x): return x
     ...
    @Identity( <any-expression> ) # smuggle in as func arg

3) I propose the following as plausible use cases (I know other people will have their own):

3.1)
    @DecoratorList[index]

3.2)
    @DecoratorDictionary[key]

3.3)
    @Decorator1 if <condition> else Decorator2
#   Special case of the last one:
    def Identity(x): return x
    @Decorator if __debug__ else Identity 

Xavier Morel has pointed out that 3.1) can be implemented now as
    @DecoratorList.__getitem__[index]
but this doesn't seem a good reason for forbidding the simpler syntax; after all Python allows the simpler syntax in other contexts.  Similarly 3.2) can be written as
    @DecoratorDictionary.get(key)

(As an aside, perhaps a decorator that evaluates to None could be treated at run-time the same as no decorator, i.e. equivalent to the Identity function in the above examples.  Currently it naturally raises TypeError: 'NoneType' object is not callable.  Just a thought.)

Finally, sorry if I have not sent this e-mail to the right place (I wanted to attach it to the 'allow lambdas as decorators' thread but don't yet know how to do this).  Also sorry that this partly duplicates a message I sent to python-dev.  I am still finding my way round the Python mailing lists.

Best wishes
Rob Cliffe
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20090906/9ca88b09/attachment.html>


More information about the Python-ideas mailing list