473,395 Members | 2,443 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,395 software developers and data experts.

__coerce__ vs. new-style classes

Why do new-style classes disable __coerce__()?
It seems cumbersome to have to write a whole set of methods (e.g.
__add__, __radd__, etc.) to get the same effect. Is there some way to
automatically generate those methods, or are we simply not supposed to
do coercion for some reason?

--
Hallvard
Jul 18 '05 #1
3 2256

"Hallvard B Furuseth" <h.**********@usit.uio.no> wrote in message
news:HB**************@bombur.uio.no...
Why do new-style classes disable __coerce__()?
It seems cumbersome to have to write a whole set of methods (e.g.
__add__, __radd__, etc.) to get the same effect. Is there some way to
automatically generate those methods, or are we simply not supposed to
do coercion for some reason?
I'm mildly confused by your example. __coerce__()
converts the arguements to a common type, and then
presumably requests that type to do the operation. That
type might not be one of the two original types!

It's not the same thing as the __op__, __rop__
pair. That simply allows the right object to do the
operation if the left object can't. (Also see 3.3.8
of the language reference for an exception to that
rule.)

The notion of type coercion makes a great deal of sense
in languages such as C, where you have 8 integer types
and 3 float types, but abstracting it out as a separate
operation makes very little sense in Python, where you
have 3 numeric types (int, long and float) and two string
types (normal and unicode). The overhead of doing
coercion as a separate operation simply doesn't make
a lot of sense.

At least, that's the way I understand it. Section 3.3.8
(Coercion Rules) of the 2.3 Language Reference gives
the official reasons for moving away from doing coercion
as part of operations. It simply got to complex to
document properly.

I suppose if you have a use case for __coerce__ in a
real world cluster of non-numeric types, you could
get Guido to reconsider.

John Roth
--
Hallvard

Jul 18 '05 #2
John Roth wrote:
"Hallvard B Furuseth" <h.**********@usit.uio.no> wrote in message
news:HB**************@bombur.uio.no...
Why do new-style classes disable __coerce__()?
It seems cumbersome to have to write a whole set of methods (e.g.
__add__, __radd__, etc.) to get the same effect. Is there some way to
automatically generate those methods, or are we simply not supposed to
do coercion for some reason?
I'm mildly confused by your example. __coerce__()
converts the arguements to a common type, and then
presumably requests that type to do the operation. That
type might not be one of the two original types!

It's not the same thing as the __op__, __rop__
pair. That simply allows the right object to do the
operation if the left object can't.


Yes:
class DeferredIntType: .... def __init__(self, fetch, *args, **kwargs):
.... def _fetch():
.... v = long(fetch(*args, **kwargs))
.... self.value = lambda: v
.... return v
.... self.value = _fetch
.... def __long__(self): return self.value()
.... def __int__(self): return int(self.value())
.... def __str__(self): return str(self.value())
.... def __coerce__(self, other):
.... if isinstance(other, (int, long)):
.... return type(other)(self.value()), other
.... DeferredIntType(len, 'foobar') + 3

9

Can't add two of them without __add__ & co, but can do just about
everything else just by writing four small methods.

If I do include __add__ & co, they won't all have to coerce the
arguments 'by hand', or worry about what to do if they don't know
how to add the type of argument they received.

Without __coerce__, what should __add__(self, other) do if it doesn't
know how to add the arguments, but the other argument might know how?
It can't just call other.__radd__(self): That might give up and call
__add__ again.
In some cases it might help to call coerce() by hand, but I note the
ref manual says 'In Python 3.0, coercion will not be supported.'.
The notion of type coercion makes a great deal of sense
in languages such as C, where you have 8 integer types
and 3 float types, but abstracting it out as a separate
operation makes very little sense in Python, where you
have 3 numeric types (int, long and float) and two string
types (normal and unicode). The overhead of doing
coercion as a separate operation simply doesn't make
a lot of sense.
Well, I was thinking of types like the above, which emulate
numeric types. The case which got me started was one which
emulates the DECIMAL (or NUMERIC) SQL type in PgSQL.py.
At least, that's the way I understand it. Section 3.3.8
(Coercion Rules) of the 2.3 Language Reference gives
the official reasons for moving away from doing coercion
as part of operations. It simply got to complex to
document properly.


I noticed that; I hadn't realized it was the argument for disabling
coercion completey.

--
Hallvard
Jul 18 '05 #3
I wrote:
Without __coerce__, what should __add__(self, other) do if it doesn't
know how to add the arguments, but the other argument might know how?
It can't just call other.__radd__(self): That might give up and call
__add__ again.
Uh... please pretend I didn't say that.
You are right, I haven't gotten coerce() straight yet.
In some cases it might help to call coerce() by hand, but I note the
ref manual says 'In Python 3.0, coercion will not be supported.'.


Even so, coerce() by hand seems pretty cumbersome. The code I could
come up with for the general case is as follows. Am I missing something
again?

class Myclass(object):
def __add__(self, other):
if not isinstance(other, Myclass):
newself, other = coerce(self, other)
if newself != self:
return newself.__add__(other)
# Or maybe the above should test if
# newself.__class__ != self.__class__, and do
# self = newself if they have the same class.
...real __add__(Myclass, Myclass) starts here...

--
Hallvard
Jul 18 '05 #4

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

Similar topics

1
by: Vetrivel | last post by:
Application architecture : Develop interface between two existing systems, a. Enterprise CRM system b. Web based intranet system. Environment : Intranet Server : IIS and ASP. Script :...
4
by: Madestro | last post by:
Hi guys, I am making a small program to retrieve e-mails from POP accounts. I got all the e-mail parsing stuff figured out, but I cannot seem to come up with a way to find out which e-mails are...
3
by: Nimmi Srivastav | last post by:
There's a rather nondescript book called "Using Borland C++" by Lee and Mark Atkinson (Que Corporation) which presents an excellent discussion of overloaded new and delete operators. I am...
20
by: Razvan | last post by:
Hi ! Is there any difference between new X and new X() ?! Regards, Razvan
2
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray =...
11
by: Jonan | last post by:
Hello, For several reasons I want to replace the built-in memory management with some custom built. The mem management itlsef is not subject to my question - it's ok to the point that I have...
2
by: Dave | last post by:
Hello all, I'd like to find a source on the web that discusses, in a comprehensive manner and in one place, everything about new / delete. It should include overloading operator new, the new...
15
by: Steve | last post by:
I have a form with about 25 fields. In the BeforeUpdate event of the form, I have code that sets the default value of each field to its current value. For a new record, I can put the focus in any...
7
by: Mike Bulava | last post by:
I have created a base form that I plan to use throughout my application let call the form form1. I have Built the project then add another form that inherits from form1, I add a few panel controls...
3
by: Grizlyk | last post by:
Hi, people. Can anybody explain me "multiple 'new' at single line" behavior. Consider: p::p(void*); p::p(void*,void*); new A( p(new B), p( new C(p(new D), p(new E)) ), p(new F));
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

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.