how to control formatting of a namedtuple in a list
Ethan Furman
ethan at stoneleaf.us
Thu Nov 17 19:18:06 EST 2016
On 11/17/2016 04:09 PM, MRAB wrote:
> On 2016-11-17 23:49, Boylan, Ross wrote:
>> Thank you; I can confirm that overriding __repr__ makes the list display as I wanted.
>>
>> The decision to use repr inside the list seems very odd, given the context, namely formatting something for display or looking for a simple string representation. It seems more natural to me to use str or, if in a format, the default formatting all the way down. Is there a good reason it's repr?
>
> Given a string, say:
>
> >>> s = 'foo'
>
> str shows:
>
> >>> print(str(s))
>
> whereas repr shows:
>
> >>> print(repr(s))
> 'foo'
>
> If it was in a list, would you want it to show:
>
> [foo]
>
> or:
>
> ['foo']
>
> ?
Another example:
>>> foo = 'ham, eggs, cheese'
>>> bar = 'bacon, toast'
if list used str instead of repr:
>>> print(list(foo, bar))
[ham, eegs, cheese, bacon, toast]
How many items are in that list? (Hint: it isn't 5. ;)
--
~Ethan~
More information about the Python-list
mailing list