I am writing a function which processes a big list of elements, and want to add the functionality that certain elements are skipped depending on an input argument. Here’s what the code looks like:
def f(lst, skipsEnabled=False):
for elem in lst:
if skipsEnabled and skipCheck(elem):
continue
else:
# do stuff to elem here
When skipsEnabled is false, the if skipsEnabled conditional can be ignored every time, however it still gets checked on every iteration and it slows my loop down. I could put the conditional before the loop, but then I’d need to duplicate the loop and this is not very OOPy since all the elem processing code would be copy-pasted in both loops.
Is there a clean way to do this?
>Solution :
Define a method to do the element processing code and then have the loop with or without the conditional and then call the same method for the processing.
It is highly unlikely that you are actually generating a large efficiency saving here, though. The skipsEnabled and skipCheck(elem) will short circuit and never call skipCheck() so it’s a single boolean check that always branches the same way. That will optimise well.