Home > Enterprise >  What is the reason for list.__str__ using __repr__ of its elements?
What is the reason for list.__str__ using __repr__ of its elements?

Time:02-01

What is the reason for list.__str__ using __repr__ of its elements?

Example:

class Unit:
    def __str__(self):  return "unit"
    def __repr__(self): return f"<unit id={id(self)}>"

>>> str(Unit())
'unit'

>>> str([Unit()])
'[<unit id=1491139133008>]'

CodePudding user response:

It's because list.__str__ is object.__str__ returns True, and object.__str__ is basically implemented like:

def __str__(self):
    return repr(self)

Unless a type implements its own __str__, it uses object.__str__.

Most builtin types in Python do not implement their own __str__, because they do not have a logical choice for a human-friendly string representation, list is no different.

CodePudding user response:

If lists used the str() of their elements rather than their repr(), then what would an output of [1, 2] mean? Is that a list with two integers, two strings, or one of each? Or is it a list with one element, the string "1, 2"? Python made the only choice that allows you to determine anything at all about the contents of a list by looking at its string representation.

  • Related