how to control formatting of a namedtuple in a list
Chris Angelico
rosuav at gmail.com
Thu Nov 17 18:24:28 EST 2016
On Fri, Nov 18, 2016 at 10:04 AM, Boylan, Ross <Ross.Boylan at ucsf.edu> wrote:
> Even after defining custom __str__ and __format__ methods they don't affect the display of objects when they are in a list. Is there a way to change that, other than explicitly converting each list element to a string?
>
Yep! Inside a list, it's the repr that gets shown. So you should be
able to do this:
class Foo(namedtuple("Foo", "x")):
def __repr__(self):
return "foolish({})".format(self.x)
This will also affect the other forms - if you don't define __str__,
it'll use __repr__. So this should be all you need.
ChrisA
More information about the Python-list
mailing list