短路结果

时间:2016-12-06 21:01:38

标签: python if-statement pep

我从PEP 532发现了以下声明:

  • __else__if表达式的短路结果   没有尾随else条款
  • __then__else表达式的短路结果   没有领先的if条款

这些陈述是什么意思?是否有任何例子可以更清楚地阐明要点?

1 个答案:

答案 0 :(得分:3)

您似乎正在阅读(约)PEP 532 - A circuit breaking operator and protocol,这是一项让左手操作数访问短路操作的提案。

Python目前无法挂钩orand布尔运算符;这些运算符短路,如果可以从左侧操作数确定结果,则不需要计算右侧操作数表达式。

例如,以下表达式不会引发异常:

count = 0
average = count and total / count

即使右手表达式在运行时会引发ZeroDivisionError异常。

PEP提出了一个新的运算符else运算符,它允许左侧的类根据它的truth-value处理操作的结果。所以在表达式中

lefthand else righthand

lefthand 可以lefthandrighthand访问,具体取决于bool(lefthand)的值。

您没有提供您找到的语句的完整上下文,但PEP 532是定义__else____then__方法的提案; type(lefthand).__then__(lefthand)被视为true时调用lefthand,否则调用type(lefthand).__else__(righthand)

result = type(lefthand).__then__(lefthand) if lefthand else type(lefthand).__else__(lefthand, righthand)

您可以将其实现为

class CircuitBreaker:
    def __bool__(self):
        # am I true or false?
        return someboolean

    def __then__(self):
        # I'm true, so return something here
        return self

    def __else__(self, righthand):
        # I'm false, the righthand has been evaluated and pass ed in
        return righthand

请注意,PEP 532 仍处于讨论中,可能是该提案从未实施过。