Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come python's __repr__ of a dict is more readable than its __str__?

See the below example:

In [33]: test = {x:str(x)*10 for x in range(10)}

In [35]: print test
{0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}

In [34]: test
Out[34]: 
{0: '0000000000',
 1: '1111111111',
 2: '2222222222',
 3: '3333333333',
 4: '4444444444',
 5: '5555555555',
 6: '6666666666',
 7: '7777777777',
 8: '8888888888',
 9: '9999999999'}

The output of the print function (__str__) is objectively less readable than the __repr__ output. It's a long line that will word-wrap into multiple lines with no spacing. Both of them are unambiguous enough to let you reconstruct the object with their output.

Wouldn't the opposite outputs make sense here, with __repr__ being the compact representation and __str__ having the more readable linebreaks?


2 Answers

This is just an ipython thing. In the standard Python 3.7 REPL this is the output:

>>> test = {x:str(x)*10 for x in range(10)}
>>> print(test)
{0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}
>>> test
{0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}
>>>

The output is the same if we execute this as a "normal" script:

test = {x: str(x) * 10 for x in range(10)}
print(str(test))
#  {0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}
print(repr(test))
#  {0: '0000000000', 1: '1111111111', 2: '2222222222', 3: '3333333333', 4: '4444444444', 5: '5555555555', 6: '6666666666', 7: '7777777777', 8: '8888888888', 9: '9999999999'}

No line breaks in either the str or repr representations, as was previously alluded to in the comments:

print(repr(test) == str(test))
# True

The conclusion is that this is just ipython taking the initiative in making repr's output more human-friendly .

like image 73
DeepSpace Avatar answered Dec 08 '25 10:12

DeepSpace


IPython does that, so print does regular stuff, but just naming variable does cool stuff, that's why...

printing pandas dataframes with print get ugly, and just naming variable does beautifully

Note that @Aran-Fey says:

"This will blow your mind: repr(test) == str(test)"

Rightfully so, non-IPython interpreters don't makes this happen.

like image 31
U12-Forward Avatar answered Dec 08 '25 11:12

U12-Forward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!