Dealing with the __str__ method in classes with lots of attributes

Andreas Tawn andreas.tawn at ubisoft.com
Thu May 10 11:15:12 EDT 2012


> On Thu, May 10, 2012 at 11:33 PM, Andreas Tawn <andreas.tawn at ubisoft.com>
> wrote:
> > Say I've got a class...
> >
> > class test(object):
> >    def __init__(self):
> >        self.foo = 1
> >        self.bar = 2
> >        self.baz = 3
> >
> > I can say...
> >
> > def __str__(self):
> >   return "foo: {0}\nbar: {1}\nbaz: {2}".format(self.foo, self.bar,
> > self.baz)
> 
> This might be of use:
> 
> return """foo: {foo}
> bar: {bar}
> baz: {baz}""".format(**self.__dict__)
> 
> You're repeating yourself a bit, but this allows the labels to differ from the format
> tags. If you're certain that you don't need that flexibility, you could generate the
> format string dynamically:
> 
> return "\n".join(x+": {"+x+"}" for x in
> ("foo","bar","baz")).format(**self.__dict__)
> 
> That scales more nicely as the number of elements desired increases (while still
> being 100% explicit - the presence and order of elements is governed by the tuple),
> but is a bit inflexible and complicated.
> I'd be inclined toward the triple-quoted-string one.

I considered the triple quote string one, but it's not very PEP 8 compatible in a real class because it includes the indentation in the formatted string.

To make it print properly, it has to look like this...

    def __str__(self):
        return """foo: {foo}
bar: {bar}
baz: {baz}""".format(**self.__dict__)

I didn't realise I could do implicit line continuation inside a list comprehension. That might be the best way.

Even more so with continuation lines inside the attribute name tuple.

    def __str__(self):
        return "\n".join(x+": {"+x+"}" for x in
            ("foo",
            "bar",
            "baz")).format(**self.__dict__)

Still feels a bit icky though.



More information about the Python-list mailing list