conditional running of code portion

Serhiy Storchaka storchaka at gmail.com
Mon Aug 6 16:59:59 EDT 2012


On 06.08.12 20:02, Dieter Maurer wrote:
> Serhiy Storchaka <storchaka at gmail.com> writes:
>> On 05.08.12 09:30, Steven D'Aprano wrote:
>>> If you are working in a tight loop, you can do this:
>>>
>>> if VERBOSE_FLAG:
>>>       for item in loop:
>>>           print(DEBUG_INFORMATION)
>>>           do_actual_work(item)
>>> else:
>>>       for item in loop:
>>>           do_actual_work(item)
>>
>> Or this:
>>
>> if VERBOSE_FLAG:
>>      def do_work(item):
>>          print(DEBUG_INFORMATION)
>>          do_actual_work(item)
>> else:
>>      do_work = do_actual_work
>>
>> for item in loop:
>>      do_work(item)
>
> Be warned: a function call is *much* more expensive than an
> "if variable:".

As any actual work. As iteration.

Yet one way:

def verbose_iter(it):
     for i in it:
         print(DEBUG_INFORMATION)
         yield i
...

if VERBOSE_FLAG:
     loop = verbose_iter(loop)
for item in loop:
     do_work(item)





More information about the Python-list mailing list