Search code examples
pythonoperatorstogglebinary-operators

Python: Concise way to toggle boolean "once" (i.e., in one direction)


I find myself needing to update a boolean variable when something happens for the first time (and only then). Using var = not var is out of the question since it would continue flip-flopping every time.

(Sorry for the silly example; I'm struggling to find a more sensible one…)

inner_has_been_two = False
for outer in range(5):
    for inner in range(3):
        if inner == 2:

            if not inner_has_been_two:
                inner_has_been_two = True

        print(inner_has_been_two)

Let's assume I want to "touch" the variable as little as possible—otherwise I could just overwrite it again and again by simply omitting the innermost if-statement.

Basically I'm looking for a more terse, pythonic way to emulate (the binary versions of the ternary conditional operator, like) the Elvis operator (?:) or a null coalescing operator (e.g. ??; varies upon language).

Any ideas on how to keep it short(er) and clear?


Solution

  • Setting it to True each time is certainly fast: a single machine cycle, likely easy to parallel process. If you want something logically like what you were trying to do:

    inner_has_been_true |= True
    

    This is also a single-cycle instruction, a "bit set" operation. It's the shorthand for

    inner_has_been_true = inner_has_been_true | True