Is there a method (similar to str() method in R) that can print the data structure in python?

Zero Piraeus schesis at gmail.com
Sun Sep 27 22:24:27 EDT 2009


:

2009/9/27 Peng Yu <pengyu.ut at gmail.com>:
>>> But I want an even simpler solution. I don't want the user to define
>>> __pretty__. Is there a tool that can automatically print the content
>>> of an object without defining such a member function like __pretty__.

Not tested (much):

from pprint import pprint

def examine(obj, limit=3):
    truncated = dict()
    for attr_name in dir(obj):
        if attr_name.startswith(("__", "_%s__" % obj.__class__.__name__)):
            continue # don't include "private" or special attributes
        attr = getattr(obj, attr_name)
        if callable(attr):
            continue # don't include methods
        if hasattr(attr, "__getitem__") and not isinstance(attr, str):
            truncated[attr_name] = attr[:limit]
        else:
            truncated[attr_name] = attr
    pprint(truncated)

It truncates sequences silently, which may or may not be what you want.

 -[]z.



More information about the Python-list mailing list