在 python 上使用字典作为装饰器
Using a dict as decorators on python
有一些方法可以使用 dict 作为装饰器 python 使用默认的 " @" 语法?
喜欢这样的东西:
from functools import wraps
def deco(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("WRAPPER")
return f(*args, **kwargs)
return wrapper
X={ "deco": deco }
# Working
@deco
def f():
pass
# Not Working: SyntaxError: invalid syntax
@X["deco"]
def y():
pass
f()
y()
如果更改为在 dict 上使用 get(),这个工作,但是不要像这样:
# Not working: SyntaxError: invalid syntax
@X.get("deco").require(http_exception=403)
def y():
pass
这个语法有一些方法可以工作or/and为什么不工作?
语法是有意限制的。见 PEP-0318:
The decorator statement is limited in what it can accept -- arbitrary
expressions will not work. Guido preferred this because of a gut feeling.
The current syntax also allows decorator declarations to call a
function that returns a decorator:
I have a gut feeling about this one. I'm not sure where it comes
from, but I have it. It may be that I want the compiler to be able to
recognize certain decorators.
So while it would be quite easy to change the syntax to @test in the
future, I'd like to stick with the more restricted form unless a real
use case is presented where allowing @test would increase readability.
(@foo().bar() doesn't count because I don't expect you'll ever need
that).
因此,该语言的 creator/lead 贡献者决定,允许任何表达式用作装饰器都会导致代码难以阅读。
也从来没有必要。你总是可以做
my_deco = X.get("deco").require(http_exception=403)
@my_deco
def somefunc():
...
有一些方法可以使用 dict 作为装饰器 python 使用默认的 " @" 语法?
喜欢这样的东西:
from functools import wraps
def deco(f):
@wraps(f)
def wrapper(*args, **kwargs):
print("WRAPPER")
return f(*args, **kwargs)
return wrapper
X={ "deco": deco }
# Working
@deco
def f():
pass
# Not Working: SyntaxError: invalid syntax
@X["deco"]
def y():
pass
f()
y()
如果更改为在 dict 上使用 get(),这个工作,但是不要像这样:
# Not working: SyntaxError: invalid syntax
@X.get("deco").require(http_exception=403)
def y():
pass
这个语法有一些方法可以工作or/and为什么不工作?
语法是有意限制的。见 PEP-0318:
The decorator statement is limited in what it can accept -- arbitrary expressions will not work. Guido preferred this because of a gut feeling.
The current syntax also allows decorator declarations to call a function that returns a decorator:
I have a gut feeling about this one. I'm not sure where it comes from, but I have it. It may be that I want the compiler to be able to recognize certain decorators.
So while it would be quite easy to change the syntax to @test in the future, I'd like to stick with the more restricted form unless a real use case is presented where allowing @test would increase readability. (@foo().bar() doesn't count because I don't expect you'll ever need that).
因此,该语言的 creator/lead 贡献者决定,允许任何表达式用作装饰器都会导致代码难以阅读。
也从来没有必要。你总是可以做
my_deco = X.get("deco").require(http_exception=403)
@my_deco
def somefunc():
...