Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use pprint to print an object using the built-in __str__(self) method?
    text
    copied!<p>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 pprint(vars(object)) function.</p> <p>The script reads the file and creates instances of a Report class. Here's the class.</p> <pre><code>class Report(object): def __init__(self, line, headers): self.date_added=get_column_by_header(line,headers,"Date Added") self.user=get_column_by_header(line,headers,"Login ID") self.report=get_column_by_header(line,headers,"Search/Report Description") self.price=get_column_by_header(line,headers,"Price") self.retail_price=get_column_by_header(line,headers,"Retail Price") def __str__(self): from pprint import pprint return str(pprint(vars(self))) </code></pre> <p>I'd like to be able to print instances of Report cleanly a-la-pprint.</p> <pre><code>for i,line in enumerate(open(path+file_1,'r')): line=line.strip().split("|") if i==0: headers=line if i==1: record=Report(line,headers) print record </code></pre> <p>When I call</p> <pre><code>print record </code></pre> <p>for a single instance of Report, this is what I get in the shell.</p> <pre><code>{'date_added': '1/3/2012 14:06', 'price': '0', 'report': 'some_report', 'retail_price': '0.25', 'user': 'some_username'} None </code></pre> <p>My question is two-fold.</p> <p>First, is this a good / desired way to print an object's attributes cleanly? Is there a better way to do this with or without pprint?</p> <p>Second, why does </p> <pre><code>None </code></pre> <p>print to the shell at the end? I'm confused where that's coming from.</p> <p>Thanks for any tips.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload