[Python-Dev] 2.4a2, and @decorators
James Y Knight
foom at fuhm.net
Tue Aug 3 06:17:43 CEST 2004
On Aug 2, 2004, at 9:05 PM, Guido van Rossum wrote:
> The first patch on SF actually had '@' test, and I requested that it
> be changed. Most things that are 'test' but not 'dotted_name'
> optionally followed by an argument list don't make sense as
> decorators; if you really have a need to write
>
> @ foo or bar
> def f(): ...
>
> you can write
>
> deco = foo or bar
> @deco
> def f(): ...
An even better workaround is to write:
def d(arg): return arg
@d(foo or bar)
def f(): ...
However, it seems as if this restriction creates a new class of
expression for no gain. It is true enough that *most* python
expressions aren't useful to write after a @, but that's also true of a
lot of other places an expression can be used (e.g. before a () of a
function call. A list comprehension can never result in a callable
object. An arithmetic operation usually won't.).
The only real necessary restriction on the @ operator is that its
argument be callable and take a single argument. Many expressions could
return a callable object. Why not let them? Is it really worth having a
special case just to SyntaxError expressions that sometimes won't
result in an appropriate callable?
Things someone might want to do, ordered roughly from most reasonable
to least reasonable ;)
@foo().bar()
@foo or bar
@mydecorators['foo']
@lambda f: foo(f) or bar(f)
Why disallow these forms? It seems quite difficult, especially, to
explain why the first one does not, or should not, work.
James
More information about the Python-Dev
mailing list