[Python-Dev] Why aren't decorators just expressions?
larry at hastings.org
Sat Sep 16 05:39:25 EDT 2017
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
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
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.
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.
/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.
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-Dev