[Python-Dev] __str__ vs. __unicode__
M.-A. Lemburg
mal at egenix.com
Wed Jan 19 13:50:04 CET 2005
Nick Coghlan wrote:
> 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:
Those APIs were all written long before there were sub-classes
of types.
> 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''
Ah, looks as if the function needs a general overhaul :-)
This section should be do a PyString_CheckExact():
if (PyString_Check(v)) {
Py_INCREF(v);
res = v;
}
But before we start hacking the function, we need a general
picture of what we think is right.
Note, BTW, that there is also a tp_str slot that serves
as hook. The overall solution to this apparent mess should
be consistent for all hooks (__str__, tp_str, __unicode__
and a future tp_unicode).
--
Marc-Andre Lemburg
eGenix.com
Professional Python Services directly from the Source (#1, Jan 10 2005)
>>> Python/Zope Consulting and Support ... http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
________________________________________________________________________
::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,FreeBSD for free ! ::::
More information about the Python-Dev
mailing list