Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does pprint show a different class from print?

Consider this example, adapted from Correct, "full length" left-right arrows in Matplotlib?:

import matplotlib.pyplot as plt
import pprint

fig = plt.figure()
ax = fig.add_subplot()
ax.plot([0],[0])
ax.grid()
ax.set_xlim([0,10])
ax.set_ylim([0,10])
ret = ax.annotate("", (2, 1), (4, 1), arrowprops={'arrowstyle':'<->', 'shrinkA': 0, 'shrinkB': 0})
print("print ret: {}".format(ret))            # print ret: Annotation(2, 1, '')
pprint.pprint("print ret: {}".format(ret))    # "print ret: Annotation(2, 1, '')"
print(ret)                                    # Annotation(2, 1, '')
pprint.pprint(ret)                            # Text(4, 1, '')
plt.show()

So, pretty much all printouts of the ret variable consider it as of class Annotation – except if I put ret directly in pprint, in which case I get a different class, Text. I find that a bit inconsistent, because I’d expect every printout of the variable to result with the same class name.

Is this expected behavior of pprint – and if so, why does it happen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

This was on MINGW64 python:

$ python3 --version
Python 3.9.7

>Solution :

When you use string formatting, implicit string conversion is applied.
class Annotation has __str__() method defined, but no __repr__().

pprint() prints the formatted representation of object (the docs), so it try to use Annotation.__repr__(), but it is not defined so it falls back to parent’s Text.__repr__() (note that Annotation inherits from Text)

You can compare the result of str(ret) and repr(ret).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading