How to use pprint to print an object using the built-in __str__(self) method?

后端 未结 5 1593
说谎
说谎 2021-02-13 16:44

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

5条回答
  •  遇见更好的自我
    2021-02-13 17:48

    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.)

提交回复
热议问题