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

Peng Yu pengyu.ut at gmail.com
Sun Sep 27 21:02:55 EDT 2009


On Sun, Sep 27, 2009 at 1:20 PM, Simon Forman <sajmikins at gmail.com> wrote:
> On Sun, Sep 27, 2009 at 12:14 PM, Peng Yu <pengyu.ut at gmail.com> wrote:
>> On Sat, Sep 26, 2009 at 2:05 PM, Robert Kern <robert.kern at gmail.com> wrote:
>>> On 2009-09-26 09:32 AM, Peng Yu wrote:
>>>>
>>>> Hi,
>>>>
>>>> I am looking for a method in python that is similar to the function
>>>> str() in R, if you are familiar with R,
>>>>
>>>> If you have no idea of R, what I want is to print the class
>>>> information of an object and the values of its members. Overloading
>>>> '__expr__' and '__repr__' then using 'print' can sort of do what I
>>>> want. But not quite. For example, if I have a list of many elements, I
>>>> don't want to print all the elements. R's str() function can
>>>> automatically take care of this issue. It also has other advantages, I
>>>> am wondering if there is something similar available in python?
>>>
>>> I use Armin Ronacher's pretty.py as a pluggable pretty-printer. You can plug
>>> into its logic to implement these kinds of tools.
>>>
>>>  http://dev.pocoo.org/hg/sandbox/file/tip/pretty
>>
>> 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__.
>>
>> Regards,
>> Peng
>
> Have you examined the pprint module?
>
> http://docs.python.org/library/pprint.html
>
> The repr module might also be of interest:
>
> http://docs.python.org/library/repr.html

Here is the example that I tried. It seems that I have to define
__expr__ to show A's member '_x'.  But this is tedious if A has many
members. I'm looking for a solution that I don't have to write
anything explicitly in a class in order to print it pretty.

$ cat main.py
import pprint

class A:
  def __init__(self):
    self._x = 10

  def show(self):
    print self._x

a = A()
a.show()

pp = pprint.PrettyPrinter()
pp.pprint(a)
$ python main.py
10
<__main__.A instance at 0x2aaaaaba2bd8>



More information about the Python-list mailing list