Skip to content Skip to sidebar Skip to footer

How To Use Pprint To Print An Object Using The Built-in __str__(self) Method?

I have a Python script which processes a .txt file which contains report usage information. I'd like to find a way to cleanly print the attributes of an object using pprint's pprin

Solution 1:

Dan's solution is just wrong, and Ismail's in incomplete.

  1. __str__() is not called, __repr__() is called.
  2. __repr__() should return a string, as pformat does.
  3. print normally indents only 1 character and tries to save lines. If you are trying to figure out structure, set the width low and indent high.

Here is an example

classS:
    def__repr__(self):
        from pprint import pformat
        return pformat(vars(self), indent=4, width=1)

a = S()
a.b = 'bee'
a.c = {'cats': ['blacky', 'tiger'], 'dogs': ['rex', 'king'] }
a.d = S()
a.d.more_c = a.c

print(a)

This prints

{   'b': 'bee',
    'c': {   'cats': [   'blacky',
                         'tiger'],
             'dogs': [   'rex',
                         'king']},
    'd': {   'more_c': {   'cats': [   'blacky',
                               'tiger'],
                  'dogs': [   'rex',
                              'king']}}}

Which is not perfect, but passable.

Solution 2:

pprint.pprint doesn't return a string; it actually does the printing (by default to stdout, but you can specify an output stream). So when you write print record, record.__str__() gets called, which calls pprint, which returns None. str(None) is 'None', and that gets printed, which is why you see None.

You should use pprint.pformat instead. (Alternatively, you can pass a StringIO instance to pprint.)

Solution 3:

pprint is just another form of print. When you say pprint(vars(self)) it prints vars into stdout and returns none because it is a void function. So when you cast it to a string it turns None (returned by pprint) into a string which is then printed from the initial print statement. I would suggest changing your print to pprint or redefine print as print if its all you use it for.

def__str__(self):
    from pprint import pprint
    returnstr(vars(self))

for i,line inenumerate(open(path+file_1,'r')):
    line = line.strip().split("|")
    if i == 0:
        headers = line
    if i == 1:
        record = Report(line,headers)
        pprint record

One alternative is to use a formatted output:

def__str__(self):
    return"date added:   %s\nPrice:        %s\nReport:       %s\nretail price: %s\nuser:         %s" % tuple([str(i) for i invars(self).values()])

Hope this helped

Solution 4:

I think beeprint is what you need.

Just pip install beeprint and change your code to:

def__str__(self):
    from beeprint import pp
    return pp(self, output=False)

Solution 5:

For pretty-printing objects which contain other objects, etc. pprint is not enough. Try IPython's lib.pretty, which is based on a Ruby module.

from IPython.lib.pretty import pprint
pprint(complex_object)

Post a Comment for "How To Use Pprint To Print An Object Using The Built-in __str__(self) Method?"