Filed Under (Python) by Marcin Kuźmiński on January-1-2010

I always loved how the print_r() function worked in php. In python print does print everything but when large collections (ie huge dicts) are printed using print you could get lost in the output. I just discovered a little smarter print function called pprint from module pprint

from pprint import pprint

This is great for debugging something in collections. Pprint prints in a nicer human readable form types of data like : list,dict,tuples.

l = [x for x in range(100)]
l.insert(0, l[:])
pprint(l)
l = dict([(x, x) for x in range(100)])

pprint(l)
#this will print this list in more convinient way
{0: 0,
 1: 1,
 2: 2,
 3: 3,
 4: 4,
 5: 5,
 6: 6,
 7: 7,
 8: 8,
 9: 9,
 ...
 98: 98,
 99: 99}

There are two interesting arguments in pprint function the:
width
Attempted maximum number of columns in the output.
width=100 will wrap everything that outputs longer than 100 chars.
and
depth
The maximum depth to print out nested structures.
ie:

pprint.pprint(stuff, depth=3)
['aaaaaaaaaa',
 ('spam', ('eggs', (...))),
 ['aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'],
 ['cccccccccccccccccccc', 'dddddddddddddddddddd']]
#now as you can see the tuples at index 1 have a depth of more than 3 and #they are being reduced by the pprint. Imagine how this helps with debuggin a
#really complicated structures.


Filed Under (Python) by Marcin Kuźmiński on July-7-2009

I found a really great beginners tutorial for Python i need to share with others. It’s python by examples.

Found at http://www.lightbird.net/py-by-example/

I read many tutorials and sites dedicated to python, but this one is absolutely a must if you’re a python beginner. It’s loaded with simple examples, and descriptions. It briefly shows you the basics of python , each function is nicely explained with few examples. If you’re interested in learning Python this is the place to start. I personally found few things i did not use and know in python like shelve or inspect.

Here is the huge list of what’s on the page:

Regards M.