confused about __str__ vs. __repr__

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Thu Dec 18 20:15:35 EST 2008


On Thu, 18 Dec 2008 22:11:27 -0200, Gabriel Genellina wrote:

> En Thu, 18 Dec 2008 14:05:32 -0200, Mikael Olofsson <mikael at isy.liu.se>
> escribió:
...
>> If I ever wanted __str__ and __repr__ to return the same thing, I would
>> make them equal:
>>
>> def __str__(self):
>>      return 'whatever you want'
>> __repr__ = __str__
>>
>> That makes it more obvious to me what's going on. As a bonus, it saves
>> one method call for every repr call.
> 
> It's even easier to define only __repr__, __str__ defaults to it:

Easier, yes, but less obvious. I can never remember whether __repr__ 
calls __str__ or __str__ calls __repr__ if one or the other is missing. 
And it costs a failed method lookup.

The method lookup is a micro-optimization, and therefore not important, 
but as far as I'm concerned the extra clarity of doing __repr__ = __str__ 
is valuable.




-- 
Steven



More information about the Python-list mailing list