Python decorator@func().attribute语法

2024-10-03 23:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在这里找到答案,但没找到。在

@obj.func # works
@obj.func(**kwargs)  #works
@obj.func1(**kwargs).func2   #-> syntax error 

我不明白为什么第三种形式是SyntaxError,对我来说似乎没有违反任何python语法,而且用户想要做什么我很清楚(见下面的示例)。在

我查看了decorator实现的pep 0318,但没有找到任何答案。在

下面是一个使用示例:

^{pr2}$

可以使用ItemFunc作为装饰器:

@ItemFunc
def plot(**kwargs):
    pass

redcross = plot.copy(color="red", marker="+")
@redcross.caller
def plot_data1(**kwargs):
    pass

bluecross = redcross.copy(color="blue")
@bluecross.caller
def plot_data2(**kwargs):
    pass

但为什么禁止使用以下“快捷语法”:

@redcross.copy(color="blue").caller
def plot_data2(**kwargs):
    pass

但我可以:

@redcross.copy_and_decorate(color="blue")
def plot_data2(**kwargs):
    pass         

第一种形式看起来更好,至少我更了解背后的意图。在


Tags: 答案objplotdefbluepass形式kwargs
1条回答
网友
1楼 · 发布于 2024-10-03 23:26:15

Function definitions grammar不允许使用更多的虚线名称调用;语法仅限于虚线名称和结尾处的可选调用

decorated      ::=  decorators (classdef | funcdef)
decorators     ::=  decorator+
decorator      ::=  "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
funcdef        ::=  "def" funcname "(" [parameter_list] ")" ":" suite
dotted_name    ::=  identifier ("." identifier)*

注意,这不是一个完整的表达式,而是一个非常有限的子集。在

这与政治公众人物计划相呼应,该计划指出:

The decorator statement is limited in what it can accept arbitrary expressions will not work. Guido preferred this because of a gut feeling [17] .

以及

The rationale for having a function that returns a decorator is that the part after the @ sign can be considered to be an expression (though syntactically restricted to just a function), and whatever that expression returns is called. See declaration arguments [16] .

强调我的。在

理由是Guido feels there isn't a real use case for allowing more

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).

您必须说服Guido和其他核心开发人员,您的案例是一个适当的用例,值得取消这些限制!在

相关问题 更多 >