how to avoid checking the same condition repeatedly ?

alex23 wuwei23 at gmail.com
Tue Oct 29 21:38:19 EDT 2013


On 28/10/2013 7:50 PM, Wolfgang Maier wrote:
> 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.

There are two approaches I would consider using here:

1. Make pre_process a decorator, and outside of the loop do:

     def pre_process_decorator(fn):
         def pre_process(x):
             # functionality goes here
             return fn(x)
         return pre_process

     if needs_processing:
         print = pre_process_decorator(print)

     for elem in iterable:
         print(elem)

2. Replace the iterable with a generator if the condition is met:

     if needs_processing:
         iterable = (pre_process(x) for x in iterable)

     for elem in iterable:
         print(elem)

Personally, I find the 2nd approach clearer.



More information about the Python-list mailing list