Problems trying to override __str__ on path class

Peter Otten __peter__ at web.de
Mon Oct 23 16:31:32 CEST 2006


Mike Krell wrote:

> Alas, the print statement says "2.1".  So there's a definite platform /
> environment difference here, but that isn't it.

It turns out the observed difference is only indirectly triggered by the
differing platforms. On my machine the path baseclass is str. If I change
it to unicode (by patching path.py), I get the same output that you had.
The problem can be reduced to

>>> class A(str):
...     def __str__(self): return "yadda"
...
>>> "%s" % A(), str(A())
('yadda', 'yadda')
>>> class B(unicode):
...     def __str__(self): return "yadda"
...
>>> "%s" % B(), str(B())
(u'', 'yadda')

So Python itself doesn't honor an overridden __str__() method for the "%s"
format. Implementing __unicode__() doesn't help, either:

>>> class C(unicode):
...     def __unicode__(self): return u"YADDA"
...     def __str__(self): return "yadda"
...
>>> "%s" % C(), unicode(C())
(u'', u'')

Somewhere there is an isinstance() test where there should be a test for the
exact class. Seems like a bug to me.

Peter




More information about the Python-list mailing list