Is there a method (similar to str() method in R) that can print the data structure in python?
nagle at animats.com
Mon Sep 28 05:04:08 CEST 2009
Zero Piraeus wrote:
> 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]
> truncated[attr_name] = attr
> It truncates sequences silently, which may or may not be what you want.
Ah, introspection. Is that a defined feature of Python or an implementation
quirk of CPython?
More information about the Python-list