Backport PR #5568: Use __qualname__ in pretty reprs for Python 3

Closes #5566.