Python has two ways to convert an object to a string: str(x)
and repr(x)
. str
is supposed to be user-readable, and repr
is more technical, e.g. for debugging purposes.
To my surprise, if I have a list of things, str(list)
and repr(list)
do the same thing and include a repr
of each item. I would expect str(list)
to include str
of the list items, and repr(list)
to include repr
of the items.
Apparently, I am not alone: back in 2008 this was proposed by Oleg Broytman and Jim J. Jewett (PEP 3140), but rejected, because “Guido said it would cause too much disturbance too close to Beta“. It is causing disturbance ever since, I suppose…
Code:
class Foo: def __init__(self, x): self.x = x def __str__(self): return f'Foo with {self.x}' def __repr__(self): return f'Foo({repr(self.x)})' foo = Foo(42) print(repr(foo)) # Foo(42) print(str(foo)) # Foo with 42 lst = [Foo(1), Foo(2)] print(repr(lst)) # [Foo(1), Foo(2)] print(str(lst)) # [Foo(1), Foo(2)] # One would expect that str() of list calls str() for each item, but it doesn't it calls repr() instead