confused about __str__ vs. __repr__

Robert Kern robert.kern at gmail.com
Thu Dec 18 16:27:17 EST 2008


Mikael Olofsson wrote:
> Diez B. Roggisch wrote:
>> Yep. And it's easy enough if you don't care about them being different..
>>
>> def __repr__(self):
>>     return str(self)
> 
> 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.

Or just define __repr__(). str() falls back to __repr__() if __str__() is not 
defined.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list