The other answer addresses repr
in a vanilla Python REPL, but it neglected to answer about IPython, which works quite differently and has many more features (and complexity) in regards to REPL printing.
Here's an example discrepancy:
# vanilla python:
>>> type([])
<class 'list'>
# in IPython:
>>> type([])
list
IPython has a custom pretty printer and public hooks for customizing repr within IPython. One such hook is _repr_pretty_
(single underscores!) and here's a basic example:
>>> class Widget:
... def __repr__(self):
... "vanilla"
... def _repr_pretty_(self, p, cycle):
... p.text("chocolate, strawberry")
...
>>> Widget()
chocolate, strawberry
For more features, see "Integrating your objects with IPython" in the docs, in particular the Rich display section.
__repr__
and__str__
. Each one returns a string that describes an object, but they don't always return the same result. – Clowerrepr
– Affluenceprint
usesstr
, and>> x
usesrepr
. – Clower