W
Wolfgang Maier
Dear all,
this is a recurring programming problem that I'm just not sure how to solve
optimally, so I thought I'd ask for your advice:
imagine you have a flag set somewhere earlier in your code, e.g.,
needs_processing = True
then in a for loop you're processing the elements of an iterable, but the
kind of processing depends on the flag, e.g.,:
for elem in iterable:
if needs_processing:
pre_process(elem) # reformat elem in place
print(elem)
this checks the condition every time through the for loop, even though there
is no chance for needs_processing to change inside the loop, which does not
look very efficient. Of course, you could rewrite the above as:
if needs_processing:
for elem in iterable:
pre_process(elem) # reformat elem in place
print(elem)
else:
for elem in iterable:
print(elem)
but this means unnecessary code-duplication.
You could also define functions (or class methods):
def pre_process_and_print (item):
pre_process(item)
print(item)
def raw_print (item):
print(item)
then:
process = pre_process_and_print if needs_processing else raw_print
for elem in iterable:
process(elem)
but while this works for the simple example here, it becomes complicated if
pre_process requires more information to do its job because then you will
have to start passing around (potentially lots of) arguments.
So my question is: is there an agreed-upon generally best way of dealing
with this?
Thanks for your help,
Wolfgang
this is a recurring programming problem that I'm just not sure how to solve
optimally, so I thought I'd ask for your advice:
imagine you have a flag set somewhere earlier in your code, e.g.,
needs_processing = True
then in a for loop you're processing the elements of an iterable, but the
kind of processing depends on the flag, e.g.,:
for elem in iterable:
if needs_processing:
pre_process(elem) # reformat elem in place
print(elem)
this checks the condition every time through the for loop, even though there
is no chance for needs_processing to change inside the loop, which does not
look very efficient. Of course, you could rewrite the above as:
if needs_processing:
for elem in iterable:
pre_process(elem) # reformat elem in place
print(elem)
else:
for elem in iterable:
print(elem)
but this means unnecessary code-duplication.
You could also define functions (or class methods):
def pre_process_and_print (item):
pre_process(item)
print(item)
def raw_print (item):
print(item)
then:
process = pre_process_and_print if needs_processing else raw_print
for elem in iterable:
process(elem)
but while this works for the simple example here, it becomes complicated if
pre_process requires more information to do its job because then you will
have to start passing around (potentially lots of) arguments.
So my question is: is there an agreed-upon generally best way of dealing
with this?
Thanks for your help,
Wolfgang