473,320 Members | 2,111 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

Problems with emulation of numeric types and coercion rules

"""
I am trying to write some classes representing the quaternion number.
I wrote a base class, which implements only the numerical interface,
and a few subclasses, which provide methods for their specific domain.

Since the operator methods will be the same for all these classes,
the base class operator methods don't explicitly return an instance
of this base class, but rather an instance of the class that called
them (ie 'return self.__class__(*args)' not 'return Quaternion(*args)')
Documentation at http://docs.python.org/ref/coercion-rules.html says:

Below, __op__() and __rop__() are used to signify the generic method
names corresponding to an operator; __iop__() is used for the
corresponding in-place operator. For example, for the operator `+',
__add__() and __radd__() are used for the left and right variant of
the binary operator, and __iadd__() for the in-place variant.

For objects x and y, first x.__op__(y) is tried. If this is not
implemented or returns NotImplemented, y.__rop__(x) is tried. If this
is also not implemented or returns NotImplemented, a TypeError
exception is raised. But see the following exception:

Exception to the previous item: if the left operand is an instance of a
built-in type or a new-style class, and the right operand is an
instance of a proper subclass of that type or class, the right
operand's __rop__() method is tried before the left operand's __op__()
method. This is done so that a subclass can completely override binary
operators. Otherwise, the left operand's __op__ method would always
accept the right operand: when an instance of a given class is
expected, an instance of a subclass of that class is always acceptable.
So I thought my plan would work. But it shows that even if the right
operand is a subclass of left operand, its __rop__() method is called
first _only_ when it overwrites the parent's method. If the method is
inherited or just copied from its parent, the rule is ignored. Here is
a simplified example:
"""

# file: number.py

def convert(obj):
if isinstance(obj, Number):
return obj._value
try:
f = float(obj)
except (TypeError, ValueError):
return NotImplemented
if f == obj:
return f
return NotImplemented
class Number(object):

def __init__(self, value=0.):
value = float(value)
self._value = value

def __add__(self, other):
"""
Return sum of two real numbers.

Returns an instance of self.__class__ so that subclasses
would't have to overwrite this method when just extending
the base class' interface.
"""
other = convert(other)
if other is NotImplemented:
return NotImplemented
return self.__class__(self._value + other)

__radd__ = __add__

# other methods
class Broken(Number):
pass
class StillBroken(Number):

__add__ = __radd__ = Number.__add__
class Working(Number):

def __add__(self, other):
return Number.__add__(self, other)

__radd__ = __add__
__doc__ = \
"""
If I now open the python interpreter::
python

Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)]
on win32
Type "help", "copyright", "credits" or "license" for more information.
from number import *
number = Number()
broken1 = Broken()
broken2 = StillBroken()
working = Working()
When the subclass is on the left side of the operator,
everything works as intended::
print type(broken1 + number).__name__ Broken print type(broken2 + number).__name__ StillBroken print type(working + number).__name__ Working

But when the sublass is on the right side of the operator, only the
subclass that has owerwritten the operator method gets called first::
print type(number + broken1).__name__ Number print type(number + broken2).__name__ Number print type(number + working).__name__

Working

According to the coercion rule, the subclass should allways be called
first. Is this a bug (either in documentation or in python), or should
I stop trying to 'upcast' the return value? I did find a solution to
this problem, but it isn't pretty and I'm not the only one using this
method. Also if this is a bug could this mail be used as a bug report?

Thanks in advance.

Ziga

"""

if __name__ == '__main__':
import doctest
doctest.testmod()

Nov 1 '05 #1
1 1723
Never mind, I forgot that class inheritance tree is a tree.
Resulting type of adding Broken and Working from previous
example would also depend on the order of operands.

Ziga

Nov 2 '05 #2

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Travis Oliphant | last post by:
Numarray is making great progress and is quite usable for many purposes. An idea that was championed by some is that the Numeric code base would stay static and be replaced entirely by Numarray. ...
4
by: Gezeala 'Eyah' Bacu\361o II | last post by:
hey guys..need your help on this.. i have a plpgsql function where in i compute numeric values for my php scripts.. my problem is my function just won't round some numbers properly.. what i...
6
by: M.A. Oude Kotte | last post by:
Hi All, I hope this is the correct mailing list for this question. But neither postgresql.org nor google could help me out on this subject. I did find one disturbing topic on the mailing list...
20
by: MLH | last post by:
120 MyString = "How many copies of each letter do you need?" 150 MyVariant = InputBox(MyString, "How Many?", "3") If MyVariant = "2" Then MsgBox "MyVariant equals the string '2'" If...
1
by: amit.amitkohli | last post by:
Hello, Am developing a web app (.Net 2.0) that can be accessed from a Pocket PC device. For testing the app, fired up the emulator from device manager (in VS2005), but when I try to use Pocket...
38
by: jdcrief | last post by:
Complier: Visual C++ 2005 Express Edition The program I wrote will compile and execute, but the output is always the same, no matter what number is entered in for the radius of the circle. ...
13
by: nishit.gupta | last post by:
Is their any fuction available in C++ that can determine that a string contains a numeric value. The value cabn be in hex, int, float. i.e. "1256" , "123.566" , "0xffff" Thnx
3
by: Jorgen Bodde | last post by:
Hi all, I have been slowly progressing with my application written in wxPython. I love the freedom, speed and lack of the compiling run. I still have to get used to the lack of (strong) types,...
8
by: Ethan Furman | last post by:
Greetings, List! I'm working on a numeric data type for measured values that will keep track of and limit results to the number of significant digits originally defined for the values in...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.