-1

I came across the following statements from PEP 532:

  • __else__ is the short-circuiting outcome for if expressions due to the absence of a trailing else clause
  • __then__ is the short-circuiting outcome for else expressions due to the absence of a leading if clause

What is meant by those statements? Are there any examples that could clarify the points a bit more?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Simplicity
  • 47,404
  • 98
  • 256
  • 385

1 Answers1

3

You appear to be reading (about) PEP 532 - A circuit breaking operator and protocol, a proposal to give the left-hand operand access to a short-circuiting operation.

Python currently has no way to hook into the or and and boolean operators; these operators short-circuit in that if the outcome can be determined from the left-hand operand, then the right-hand operand expression doesn't need to be evaluated.

For example, the following expression won't raise an exception:

count = 0
average = count and total / count

even though the right-hand expression would raise a ZeroDivisionError exception if run.

The PEP proposes a new operator, the else operator, that'll let the class of the left-hand side handle the outcome of the operation based it's truth-value. So in the expression

lefthand else righthand

the lefthand class is given access to either lefthand or righthand depending on the value of bool(lefthand).

You didn't give the full context of the statements you found, but PEP 532 is the proposal that defines the __else__ and __then__ methods; type(lefthand).__then__(lefthand) is called when lefthand is considered true, otherwise type(lefthand).__else__(righthand) is called:

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

You can implement these then as

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

Note that PEP 532 is still under discussion and it may be that this proposal is never implemented.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343