The last line of output below shows that when I format the list I get standard formatting of my objects instead of my custom format.
Code
#! /usr/bin/python3
from collections import namedtuple
class Foo(namedtuple("Foo", "x")):
__slots__ = ()
def __str__(self):
return "foolish({})".format(self.x)
def __format__(self, spec):
return self.__str__()
f=Foo(4)
print(f)
print(str(f))
print("{}".format(f))
print("{}".format([f])) # a list with one f
Output
foolish(4)
foolish(4)
foolish(4)
[Foo(x=4)]
I'm running Python 3.4.
Thanks.
Ross
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?
Ross
________________________________________
From: Python-list [python-list-bounces+ross.boylan=ucsf...@python.org] on behalf of Chris Angelico [ros...@gmail.com]
Sent: Thursday, November 17, 2016 3:24 PM
To: pytho...@python.org
Subject: Re: how to control formatting of a namedtuple in a list
ChrisA
--
https://mail.python.org/mailman/listinfo/python-list
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...@python.org] on behalf of Ethan Furman [et...@stoneleaf.us]
Sent: Thursday, November 17, 2016 4:18 PM
To: pytho...@python.org
Subject: Re: how to control formatting of a namedtuple in a list
On 11/17/2016 04:09 PM, MRAB wrote:
Another example:
--
~Ethan~
--
https://mail.python.org/mailman/listinfo/python-list