Python is faster than C

Raymond Hettinger python at rcn.com
Mon Apr 5 02:49:56 EDT 2004


[Jeff Epler]
> from pprint import *
> def install_hook():
>     def displayhook(v):
>         import __main__
>         if v is not None:
>             if isiterator(v):
>                 print "<%s object at 0x%8x:" % (
>                     type(v).__name__, id(v)),
>                 v, copy = itertools.tee(v)
>                 for elem in itertools.islice(copy, 3):
>                     print saferepr(elem),
>                 try:
>                     copy.next()
>                 except StopIteration:
>                     pass
>                 else:
>                     print '...',
>                 sys.stdout.softspace=0
>                 print ">" 
>             else:
>                 pprint(v)
>         __main__._ = v
> 
>     sys.displayhook = displayhook

This is very nice.

In my sketch, I used Py2.4's itertools.tee() to handle non-restartable
iterators.  For Py2.3, a good alternative is:

copy = list(itertools.islice(v, 3))
v = itertools.chain(copy, v)

Now, copy can be used in the display and "v" produces the same values
as the original iterator.


Cheers,

Raymond Hettinger


P.S.  If some experimentation shows your code to be useful at the
interactive prompt, please submit a patch on SF so it won't be lost.



More information about the Python-list mailing list