The syntax for decorators in the grammar is quite specific:
decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
Decorators can be either a dotted name, or a dotted name followed by
arguments. This disallows:
@mapping['async'] # looking something up in a mapping
@func(1, 2, 3).async # getting the attribute of the result
of a function call
Obviously these restrictions haven't been too burdensome, as I've
labored under them for 13+ years and didn't even notice until just
now. But it set me to wondering.
If it were me, perpetually lazy sod that I am, I'd have written the
grammar as
decorator: '@' expr NEWLINE
and been done with it.
So why don't decorators allow arbitrary expressions? The PEP
discusses the syntax for decorators, but that whole debate only
concerned itself with where the decorator goes relative to "def",
and what funny punctuation might it use. It never says "decorators
shouldn't permit arbitrary expressions because--". Nor is there any
info on wiki page with the extensive summary of alternative syntax
proposals.
Anybody remember?
I'm not proposing that we allow arbitrary expressions as
decorators... well, I'm not doing that yet at least. But
like I said, the syntax has been this way for 13 years and I don't
recall anybody complaining.
/arry
p.s. I experimentally tried modifying the grammar for
descriptors to allow arbitrary expressions. The syntax was fine but
it crashed in ast_for_decorator(). When I updated that to match, it
worked fine! The diff is short and mainly consists of deleted code.