Walter Dörwald wrote: > __str__ and __unicode__ seem to behave differently. A __str__ > overwrite in a str subclass is used when calling str(), a __unicode__ > overwrite in a unicode subclass is *not* used when calling unicode(): > > ------------------------------- > class str2(str): > def __str__(self): > return "foo" > > x = str2("bar") > print str(x) > > class unicode2(unicode): > def __unicode__(self): > return u"foo" > > x = unicode2(u"bar") > print unicode(x) > ------------------------------- > > This outputs: > foo > bar > > IMHO this should be fixed so that __unicode__() is used in the > second case too. If you drop the base class for unicode, this already works. This code in object.c:PyObject_Unicode() is responsible for the sub-class version not doing what you'd expect: if (PyUnicode_Check(v)) { /* For a Unicode subtype that's not a Unicode object, return a true Unicode object with the same data. */ return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v), PyUnicode_GET_SIZE(v)); } So the question is whether conversion of a Unicode sub-type to a true Unicode object should honor __unicode__ or not. The same question can be asked for many other types, e.g. floats (and __float__), integers (and __int__), etc. >>> class float2(float): ... def __float__(self): ... return 3.141 ... >>> float(float2(1.23)) 1.23 >>> class int2(int): ... def __int__(self): ... return 42 ... >>> int(int2(123)) 123 I think we need general consensus on what the strategy should be: honor these special hooks in conversions to base types or not ? Maybe the string case is the real problem ... :-) -- 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 ! ::::
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4