Search code examples
pythonwalrus-operator

Warlus Operator conversion


I have a piece of code involving walrus operator. I am trying to convert it to normal python code. But I am not sure if it is happening correctly or not.

# code with warlus
NUM_ELEMS = cpu_count()
NUM_CORES = len(list_of_data)

fair_core_worload = NUM_ELEMS // NUM_CORES
cores_with_1_more = NUM_ELEMS % NUM_CORES

EXTENTS_OF_SUBRANGES = []
bound = 0

for i, extent_size in enumerate(
    [fair_core_worload + 1 for _ in range(cores_with_1_more)]
    + [fair_core_worload for _ in range(NUM_CORES - cores_with_1_more)]
):
    
    EXTENTS_OF_SUBRANGES.append((bound, bound := bound + extent_size))

According to my understanding, it should be working with this code.

for i, extent_size in enumerate(
    [fair_core_worload + 1 for _ in range(cores_with_1_more)]
    + [fair_core_worload for _ in range(NUM_CORES - cores_with_1_more)]
):
    bound = extent_size
    bound_extended = bound + extent_size
    EXTENTS_OF_SUBRANGES.append((bound, bound_extended))

I do not have python3.8 to test the walrus code.


Solution

  • EXTENTS_OF_SUBRANGES.append((bound, bound := bound + extent_size))
    

    can be destructured into:

    temp = bound + extent_size
    EXTENTS_OF_SUBRANGES.append((bound, temp))
    bound = temp