Search code examples
pythoncoding-stylereadability

Most pythonic way to express a variable that switches exclusively through two 'named' values


I have a iteration that is quite complicated, and each time through the loop, I have need for a 'parameter' that effects the work done in the loop. Basically, I have been doing the following:

CLOSE_SIDE = 0
FAR_SIDE = 1

....

while (...):
    if (side == CLOSE_SIDE):
        ....
    else if (side == FAR_SIDE):
        ....

    ....

    side = FAR_SIDE if (side == CLOSE_SIDE) else CLOSE_SIDE

I realize I could just use a boolean, but I feel like that reduced the readability and obviousness of what I'm doing. I would like the two states to be 'named'. Also the assignment, though compact, feels very clunky. And doing a whole if statement:

if side == CLOSE_SIDE:
    side = FAR_SIDE
else if side == FAR_SIDE:
    side = CLOSE_SIDE

feels equally as clunky.

What is the best way to approach this? It's more of a stylistic problem than anything. Would like some opinions from the community


Solution

  • Instead of naming the two values, you could choose an appropriate name for a bool variable and switch it between True and False:

    while (...):
        if far:
            ....
        else:
            ....
    
        ....
    
        far = not far