I've got a list of several instances of the same python object that I want to loop through and perform 3 of the methods on; however, there are situations I want to select which of the 3 to run (in any combination).
I could do something like this:
do_method_1 = True
do_method_2 = True
do_method_3 = True
for item in list_of_items:
if do_method_1:
item.method_1()
if do_method_2:
item.method_2()
if do_method_2:
item.method_2()
It's easy to read but, I'm doing each check multiple times for each item in the loop and slowing things down a little. I could also flip it by doing each check and then loop through the items for each True/False check... but then I'm potentially looping through everything multiple times and slowing things down that way.
I'm curious if there's an easy way to only evaluate the checks and the loop once. I've currently got something like this:
do_method_1 = True
do_method_2 = True
do_method_3 = True
if do_method_1:
if do_method_2:
if do_method_3:
for item in list_of_items:
item.method_1()
item.method_2()
item.method_3()
else:
for item in list_of_items:
item.method_1()
item.method_2()
elif do_method_3:
for item in list_of_items:
item.method_1()
item.method_3()
else:
for item in list_of_items:
item.method_1()
else:
if do_method_2:
if do_method_3:
for item in list_of_items:
item.method_2()
item.method_3()
else:
for item in list_of_items:
item.method_2()
elif do_method_3:
for item in list_of_items:
item.method_3()
else:
print('not doing anything...')
This does work out so that the loop is only executed once, and I think each check would technically only get evaluated once, but it's a lot of repeat code clutter and would become even more of a headache to write/read if a 4th method was added to the list of possibilities. So, is there another way to write this out that's 'cleaner' to do the loop only once and do each check only once for speed?
Thanks!