3

In python, is there a section of a PEP against the method __str__ returning a multiline string?

Pro: PyCharm does not tell me off and Google draws a blank

Contra: I could see it would cause an inelegant response if someone concatenated it, feels un-pythonic and I am not sure I can recall seeing one β€”bar in my own code

So I am not sure if to just have a multiline __str__ return (keep it simple) or to leave alone __str__ (i.e. returns <class foo>) and have a special module (e.g. foo.report()).

200_success
  • 7,286
  • 1
  • 43
  • 74
Matteo Ferla
  • 2,128
  • 1
  • 16
  • 27
  • Possible duplicate of [Difference between \_\_str\_\_ and \_\_repr\_\_ in Python](http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python) – Nathaniel Ford Mar 25 '16 at 21:10
  • 1
    I don't think this is a `__str__` vs `__repr__` dupe though, if anything, it's more of an opinion based question. But I guess you could also say that it already has an answer – Bahrom Mar 25 '16 at 21:15

2 Answers2

6

There's nothing wrong with it. There are plenty of classes that return multiline values for str (such as pandas DataFrames and Series). You can return whatever format you think best represents the object.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
2

The __str__ method is meant to return a string value that is human readable. If there is any use in having multiple lines for that (such as the string representation of a board game that has two dimensions), you should do that. If it is meant to be consumed by another source, you may want to use a custom method that includes the appropriate information in the appropriate format, or override __repr__, which is meant to return an unambiguous string representation.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102