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