[Python-Dev] pprint(iterator)

Raymond Hettinger python at rcn.com
Tue Jan 27 22:46:35 CET 2009


It is becoming the norm in 3.x for functions to return iterators, generators, or views whereever possible.

I had a thought that pprint() ought to be taught to print iterators:

    pprint(enumerate(seq))
    pprint(map(somefunc, somedata))
    pprint(permutations(elements))
    pprint(mydict.items())

Currently, all four of those will print something like:

    >>> pprint(d.items())
    <dict_items object at 0x00FA4470>
    >>> pprint(enumerate(d))
    <enumerate object at 0x00FC2878>

If pprint() is to give a more useful result, the question is how best to represent the iterators.

In the examples for itertools, I adopted the convention of displaying  results
like a collection with no commas or enclosing delimiters:

    # chain('ABC', 'DEF') --> A B C D E F

The equivalent for pprint would be the same for items, using space for items on one row or using linefeeds for output too long for 
one row.

Another idea is to make-up an angle-bracket style to provide a visual cue for iterator output:

    <'A' 'B' 'C' 'D' 'E' 'F'>

Perhaps with commas:

    <'A', 'B', 'C', 'D', 'E', 'F'>

None of those ideas can be run through eval, nor do they identify the type of iterator.  Perhaps these would be better:

    <enumerate object: 'A', 'B', 'C', 'D', 'E', 'F'>

or

   iter(['A', 'B', 'C', 'D', 'E', 'F'])


Do you guys have any thoughts on the subject?


Raymond 



More information about the Python-Dev mailing list