[Python-Dev] __str__ vs. __unicode__

Nick Coghlan ncoghlan at iinet.net.au
Wed Jan 19 13:26:14 CET 2005


M.-A. Lemburg wrote:
>> So if we fix __str__ this would be a bugfix for 2.4.1.
>> If we fix the rest, this would be a new feature for 2.5.
> 
> 
> I have a feeling that we're better off with the bug fix than
> the new feature.
> 
> __str__ and __unicode__ as well as the other hooks were
> specifically added for the type constructors to use.
> However, these were added at a time where sub-classing
> of types was not possible, so it's time now to reconsider
> whether this functionality should be extended to sub-classes
> as well.

It seems oddly inconsistent though:

"""Define __str__ to determine what your class returns for str(x).

NOTE: This won't work if your class directly or indirectly inherits from str. If 
that is the case, you cannot alter the results of str(x)."""

At present, most of the type constructors need the caveat, whereas __str__ 
actually agrees with the simple explanation in the first line.

Going back to PyUnicode, PyObject_Unicode's handling of subclasses of builtins 
is decidedly odd:

Py> class C(str):
...   def __str__(self): return "I am a string!"
...   def __unicode__(self): return "I am not unicode!"
...
Py> c = C()
Py> str(c)
'I am a string!'
Py> unicode(c)
u''

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net


More information about the Python-Dev mailing list