[Python-Dev] __str__ vs. __unicode__
Walter Dörwald
walter at livinglogic.de
Thu Feb 24 16:32:28 CET 2005
Brett C. wrote:
> Walter Dörwald wrote:
>
>> M.-A. Lemburg wrote:
>>
>>> [...]
>>> I don't have a clear picture of what the consensus currently
>>> looks like :-)
>>>
>>> If we're going for for a solution that implements the hook
>>> awareness for all __<typename>__ hooks, I'd be +1 on that.
>>> If we only touch the __unicode__ case, we'd only be created
>>> yet another special case. I'd vote -0 on that.
>>> [...]
>>
>> Here's the patch that implements this for int/long/float/unicode:
>> http://www.python.org/sf/1109424
>
> Any movement on this? +1 for making things work like str; if a subclass
> overrides __str__ it should use that method. If correctness of what is
> returned is a worry then a check could be tossed in before the value is
> returned.
It already works that way:
Python 2.5a0 (#1, Feb 24 2005, 16:25:04)
[GCC 2.96 20000731 (Red Hat Linux 7.3 2.96-113)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class u(unicode):
... def __unicode__(self): return 42
...
>>> unicode(u("foo"))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: coercing to Unicode: need string or buffer, int found
>>> class i(int):
... def __int__(self): return "foo"
...
>>> int(i(42))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __int__ returned non-int (type str)
>>> class l(long):
... def __long__(self): return "foo"
...
>>> long(l(42))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __long__ returned non-long (type str)
>>> class f(float):
... def __float__(self): return "foo"
...
>>> float(f(42))
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: __float__ returned non-float (type str)
Bye,
Walter Dörwald
More information about the Python-Dev
mailing list