Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #26659

Re: conditional running of code portion

From Serhiy Storchaka <storchaka@gmail.com>
Subject Re: conditional running of code portion
Date 2012-08-06 23:59 +0300
References <0a61aed2-bd14-4022-bf59-a3bb3af55b3c@sn4g2000pbc.googlegroups.com> <501e1319$0$29978$c3e8da3$5496439d@news.astraweb.com> <jvm7ma$kdf$1@dough.gmane.org> <87hasg0x9b.fsf@handshake.de>
Newsgroups comp.lang.python
Message-ID <mailman.3032.1344286818.4697.python-list@python.org> (permalink)

Show all headers | View raw


On 06.08.12 20:02, Dieter Maurer wrote:
> Serhiy Storchaka <storchaka@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)

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

conditional running of code portion JW Huang <ngcbmy@gmail.com> - 2012-08-04 21:16 -0700
  Re: conditional running of code portion Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2012-08-05 06:30 +0000
    Re: conditional running of code portion Serhiy Storchaka <storchaka@gmail.com> - 2012-08-05 19:40 +0300
    Re: conditional running of code portion Dieter Maurer <dieter@handshake.de> - 2012-08-06 19:02 +0200
    Re: conditional running of code portion Serhiy Storchaka <storchaka@gmail.com> - 2012-08-06 23:59 +0300
  Re: conditional running of code portion "Steven W. Orr" <steveo@syslang.net> - 2012-08-05 22:50 -0400

csiph-web