[Python-bugs-list] [ python-Bugs-511603 ] Error calling str on subclass of int

noreply@sourceforge.net noreply@sourceforge.net
Thu, 31 Jan 2002 23:52:57 -0800


Bugs item #511603, was opened at 2002-01-31 23:31
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=511603&group_id=5470

Category: Type/class unification
Group: Python 2.2
Status: Open
Resolution: None
Priority: 5
Submitted By: Nicholas Socci (nsocci)
Assigned to: Nobody/Anonymous (nobody)
Summary: Error calling str on subclass of int

Initial Comment:
Not sure if this is a bug or my misunderstanding of 
str() and repr(). This work:

class Bfloat(float):
    def __repr__(self):
        return(str(self))

bf=Bfloat(1.0)
print bf

so does subclassing long, float, and str
but the following causes and infinite recursion

class Bint(int):
    def __repr__(self):
        return(str(self))

bi = Bint(1)


Version Info:
Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit 
(Intel)] on win32
Type "copyright", "credits" or "license" for more 
information.


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

>Comment By: Tim Peters (tim_one)
Date: 2002-01-31 23:52

Message:
Logged In: YES 
user_id=31435

Well, the difference with long, float and str is that they 
have *distinct* repr and str implementations.  int does 
not:  repr and str are exactly the same function for int, 
so calling str inside an int subclass repr implementation 
is really calling repr again (just with a different 
*name*).  The same is true of, e.g., the dict type, which 
also uses the same function for str and repr (so you'd also 
see unbounded recursion if you tried a similar thing with a 
dict subtype).

This uncomfortably clumsly to explain, so maybe there's 
room for improvement.  In the meantime, since str and repr 
*are* the same for ints, you could write

class Bint(int):
.   def __repr__(self):
.       return int.__repr__(self)

Calling a base class method would be clearer anyway, and in 
all your examples.

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

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