[C++-sig] V2: coerce method howto?

David Abrahams david.abrahams at rcn.com
Mon Apr 22 17:48:33 CEST 2002


Hi Pearu,

----- Original Message -----
From: "Pearu Peterson" <pearu at cens.ioc.ee>


> I have managed to put together a working coerce method (shown at the
end
> of this message) but then to my surprise I found that it has no
effect:
>
> >>> coerce(ex(1),2.3)
> (ex(numeric('1')), ex(numeric('2.2999999999999998224')))
> >>> ex(1).__add__(ex(2))
> ex(numeric('3'))
> >>> ex(1)+2.3
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> TypeError: bad argument type for built-in operation
>
> Any ideas?

Yes, as a matter of fact:

Python 2.2 (#28, Mar 13 2002, 23:18:18) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> coerce
<built-in function coerce>
>>> class ex(object):
...     def __init__(self, v):
...             self.v = v
...     def __coerce__(self, other):
...             return self, ex(other)
...     def __add__(self, rhs):
...             return ex(self.v + rhs.v)
...     def __repr__(self):
...             return 'ex(' + repr(self.v) + ')'
...
>>> ex(3)
ex(3)
>>> coerce(ex(1),2.3)
(ex(1), ex(2.2999999999999998))
>>> ex(1).__add__(ex(2))
ex(3)
>>> ex(1)+2.3
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 9, in __add__
AttributeError: 'float' object has no attribute 'v'

Which is reminiscent of the following:

http://aspn.activestate.com/ASPN/Mail/Message/1168234.

I think a bug report to sourceforge might be appropriate. I've asked
about this on python-dev and post the bug to the SF bug tracker if
nobody tells me I'm crazy.

> Pearu
>
> PS: I hope that I am not too annoying with my experiments with V2 ;)

No, please keep them coming!
BTW I think we want coerce support much more like what is provided by
Boost.Python v1, so you shouldn't have to write those functions
manually.

-Dave






More information about the Cplusplus-sig mailing list