My (late) beef with Simple Generator syntax (PEP 255)

Alex Martelli aleax at aleax.it
Thu Nov 14 17:25:19 EST 2002


Neil Schemenauer wrote:

> Just wrote:
>> IMO the best idiom for this currently is
>> 
>>   def foo():
>>       while 0:
>>           yield "whatever"
> 
> This whole discussion is silly, IMHO.  The best idiom is:
> 
>     def foo():
>         return []

Actually, I suspect returning () instead -- empty tuple, not
empty list -- is even better.  To wit:

import time

def emptylist(): return []
def emptytuple(): return ()

def timit(func):
    repeater = [None] * (100*1000)
    start = time.clock()
    for x in repeater: func()
    stend = time.clock()
    return '%s %.2f' % (func.func_name, stend-start)

for f in (emptylist, emptytuple) * 3:
    print timit(f)

[alex at lancelot ball]$ python2.2 -O ba.py
emptylist 0.16
emptytuple 0.07
emptylist 0.14
emptytuple 0.08
emptylist 0.15
emptytuple 0.07
[alex at lancelot ball]$ python2.3 -O ba.py
emptylist 0.08
emptytuple 0.07
emptylist 0.07
emptytuple 0.05
emptylist 0.08
emptytuple 0.07
[alex at lancelot ball]$

admittedly the difference is going to be even less in 2.3,
but still, it's about 100 milliseconds per million empties one
returns -- a few billions, and we'd be talking about REAL
performance issues.  Surely any implementation of something
as frequent as "returning an empty iterable" cannot aspire
to the title of "the best" with that sort of performance hit.


[Note for the humor-impaired: I'd gladly sprinkle suitable
emoticons throughout the post, but unfortunately my Linux
installation doesn't seem to have /dev/emoticons right now --
must be devfs up to its usual tricks -- sorry].


Alex




More information about the Python-list mailing list