Can __str__
return literally anything my soul desires?
The documentation on __str__ states:
[...] the “informal” or nicely printable string representation of an object
How should one interpret it?
- A. That it can return anything as long as in my opinion it represents the object.
- B. That it should return unambiguous representation of the object, albeit it can be formatted in any way I please.
Example of A:
class Vehicle:
def __init__(self, owner):
self.owner = owner
self.wheels = 4
def __str__(self):
return "%s with %s wheels" % (self.owner, self.wheels)
print(Vehicle('Benjamin'))
>>> Benjamin with 4 wheels
Example of B:
class Vehicle:
def __init__(self, owner):
self.owner = owner
self.wheels = 4
def __str__(self):
return "Vehicle, owner is %s, with %s wheels" % (self.owner, self.wheels)
print(Vehicle('Benjamin'))
>>> Vehicle, owner is Benjamin, with 4 wheels
Just about all resources I find (1, 2, 3, 4, 5, 6) suggest that the output - while it can be informal - should be unambiguous and explicit (and it makes sense: Explicit is better than implicit., Readability counts. In the face of ambiguity, refuse the temptation to guess.).
However there are a few that suggest that one could in fact be ambiguous and implicit (1, 2) given the 'informal' word in the documentation. I found one fellow developer who states that one can use absolutely any representation of the object in __str__
, and that __repr__
is for unambiguous and explicit representations. I'd like to understand their perspective but can't find any reasoning supporting their case. Can you suggest how one should interpret that documentation and support your reasoning?