[Python-bugs-list] [ python-Bugs-479698 ] __coerce__ not working with new classes

noreply@sourceforge.net noreply@sourceforge.net
Mon, 26 Nov 2001 07:59:35 -0800


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

Category: Type/class unification
Group: Python 2.2
Status: Open
Resolution: None
Priority: 7
Submitted By: Nobody/Anonymous (nobody)
Assigned to: Guido van Rossum (gvanrossum)
Summary: __coerce__ not working with new classes

Initial Comment:
I converted a numeric-like class from the "old-style"
Python class to the "new-style" Python class by
inheriting from "object".  Numerical operations like
"__mul__" and "__div__" failed with the "new-style"
class.  After tracking the problem, I found that the
"__coerce__" special method was called when performing
mixed-type arithmetic, as expected, with the
"old-style" class, but not with the "new-style" class. 
The arithmetic operations failed because the expected
type conversion was not performed with the mixed-type
arithmetic.  As best I can tell, without examining the
Python source code, the following is taking place:

1.  The documentation for the "__coerce__" special
method states that it is invoked in the case of
mixed-type arithmetic only if at least one of the
arguments in an arithmetic operation is a class
instance.

2.  An object created with an "old-style" class is of
type "instance", as verified by the "type" function,
i.e.
    <type 'instance'>

3.  An object created with a "new-style" class is of a
different type, as also verified by the "type function,
i.e.
    <class '.....'>

Evidently, because of this change in type, the
"__coerce__" function is not longer invoked for
"new-style" Python classes.

Gary H. Loechelt
ON Semiconductor


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

Comment By: Gary H. Loechelt (loechelt)
Date: 2001-11-26 07:59

Message:
Logged In: YES 
user_id=142817

After further looking into this, I am not sure that it is a
bug "per se".  It may have been the intentionally designed
behavior.  It is certainly possible for a user to rewrite
arithmetic methods (i.e. '__add__') to explicitly call a
coerce method.  However, in the very least, changing from
the "old-style" to the "new-style" class does break existing
code that relies upon the '__coerce__' method, and this fact
is not very well documented.

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

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