0

I am having trouble understanding why the default __repr__'s implementation isn't more informative.

This answer on https://stackoverflow.com/a/2626364/3646408 states

having a default for repr which would act like: return "%s(%r)" % (self.__class__, self.__dict__) would have been too dangerous (for example, too easy to get into infinite recursion if objects reference each other).

Such case would be

instance = Class(); instance.attr = instance

This seems like more a mistake to me. What could be a valid use-case where this could happen?

Community
  • 1
  • 1
Abhishek Bhatia
  • 9,404
  • 26
  • 87
  • 142

3 Answers3

2

That is a valid use case for some hierarchical structure, when node can have children that reference their parent

As an example,

root = Node()
child = Node()
child.parent=root
root.children = [child]
Lol4t0
  • 12,444
  • 4
  • 29
  • 65
2

Consider a DOM tree where a node contains references to its children, and every child contains a reference to its parent.

(It also happens between siblings via nextSibling/previousSibling.)

melpomene
  • 84,125
  • 8
  • 85
  • 148
2

This could happen with any type of object with bidirectional references. For instance, a class that represents family relationships, where each person has a reference to their spouse, or where parents have references to their children and children have references to their parents.

PHP's print_r() does what you suggest; see Recursion using PHP Simple DOM Parser for the problem someone had trying to print the object that represents an HTML DOM element.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612