how to control formatting of a namedtuple in a list

Boylan, Ross Ross.Boylan at ucsf.edu
Thu Nov 17 20:39:07 EST 2016


Actually,
>> print(list(foo, bar))
Traceback (most recent call last):                                                                                              
  File "<stdin>", line 1, in <module>                                                                                           
TypeError: list() takes at most 1 argument (2 given)       

Though                                                                     
>>> [foo, bar]
['ham, eggs, cheese', 'bacon, toast'] 
which admittedly would be confusing if the strings weren't quoted. But display, or formatted values, are not intended to allow reconstruction of the objects; that's what repr is for. 

The argument that the display of list is already low-level, and so everything inside the list should be displayed low-level, seems a bit of a stretch.

Overriding repr is serviceable for me, but it requires violating the intended semantics of repr, namely that the result could be converted back to the original object. I'm trying to get a display that has only some of the information in the object.  My understanding is that str is supposed to provide that.

At any rate, I agree there are reasons to use repr inside a list.

Ross
________________________________________
From: Python-list [python-list-bounces+ross.boylan=ucsf.edu at python.org] on behalf of Ethan Furman [ethan at stoneleaf.us]
Sent: Thursday, November 17, 2016 4:18 PM
To: python-list at python.org
Subject: Re: how to control formatting of a namedtuple in a list

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~
--
https://mail.python.org/mailman/listinfo/python-list



More information about the Python-list mailing list