[Python-bugs-list] [ python-Bugs-468061 ] __str__ ignored in str subclass

noreply@sourceforge.net noreply@sourceforge.net
Thu, 04 Oct 2001 13:52:35 -0700


Bugs item #468061, was opened at 2001-10-04 13:52
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=468061&group_id=5470

Category: Type/class unification
Group: Python 2.2
Status: Open
Resolution: None
Priority: 5
Submitted By: Tim Peters (tim_one)
Assigned to: Guido van Rossum (gvanrossum)
Summary: __str__ ignored in str subclass

Initial Comment:
>From c.l.py; looks messy (e.g., if PyObject_String 
didn't ignore octetstring.__str__, the call to str() 
in the latter would just recurse forever; and he's 
right that b2a_hex requires a genuine string; and e.g.

    return b2a_hex(self + "")

would be mighty obscure).

 ----Original Message-----
From: Andreas.Trawoeger
Sent: Thursday, October 04, 2001 7:10 AM
To: python-list
Subject: Python 2.2a4: Problems with overloading 
__str__ in subclasses of str

I would like to write a class that behaves like a 
string only with the difference that it displays the 
string in hex.  In Python 2.2a4 this should be 
possible by subclassing str and overloading __repr__ 
and __str__ :

from binascii import b2a_hex

class octetstring(str):
    def __repr__(self):
        return b2a_hex(str(self))
    def __str__(self):
        return b2a_hex(str(self))

o = octetstring('A')

print "o.__repr__():",o.__repr__()
print "o.__str__() :",o.__str__()
print "str(o)      :",str(o)
print "o           :",o

The result is pretty strange:

o.__repr__(): 41
o.__str__() : 41
str(o)      : A
o           : A

I'm not shure what's the exact reason for this 
problem. Either __str__ isn't used for str() and 
print.  Or I'm trapped in an chicken egg problem:
I have to convert self to an string (otherwise b2a_hex 
won't work) to do this Python should use __str__ 
(which is the method I'm changing).

cu andreas


----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=468061&group_id=5470