Dealing with the __str__ method in classes with lots of attributes

Chris Angelico rosuav at gmail.com
Thu May 10 17:47:03 EDT 2012


On Fri, May 11, 2012 at 1:15 AM, Andreas Tawn <andreas.tawn at ubisoft.com> wrote:
> 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.

Yeah, that is an annoying side effect. My personal view is that code
should be written concisely, even if that means violating indentation.
One possible way around that is to break out the format string to a
module variable (thus completely unindented); another way is to accept
the indentation, for instance:

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

resulting in a string that has a somewhat Pythonic syntax to it. Would
work nicely if you have a few "primary" attributes that go onto the
first line, and a bunch of "secondary" attributes that get listed
below.

ChrisA



More information about the Python-list mailing list