473,804 Members | 3,126 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__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 2280

"Hallvard B Furuseth" <h.**********@u sit.uio.no> wrote in message
news:HB******** ******@bombur.u io.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.**********@u sit.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(*arg s, **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(othe r, (int, long)):
.... return type(other)(sel f.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(othe r, 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
7991
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 : VBScript and Javascript Client : 1. IE browser. 2. VBForm embedded with WebBrowser control (MS Internet
4
1831
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 NEW so I don't have to retrieve them all. If you have experience with this kind of thing, you know that the server creates unique IDs for all the messages, but this IDs are not guaranteed to be unique, since they can be reused once a message is...
3
9420
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 presenting below a summary of what I have gathered. I would appreciate if someone could point out to something that is specific to Borland C++ and is not supported by the ANSI standard. I am also concerned that some of the information may be outdated...
20
1846
by: Razvan | last post by:
Hi ! Is there any difference between new X and new X() ?! Regards, Razvan
2
7673
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 = (data_type**)malloc(widht*height*sizeof(data_type)+ height* sizeof(data_type*)); //allocate individual addresses for row pointers. Now that I am moving to C++,am looking for something by which I can
11
912
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 nice and working allocation deallocation routines. However, I don't want to loose the nice extras of new operator, like - constructor calling, typecasting the result, keeping the array size, etc. For another bunch of reasons, outside this scope I...
2
2093
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 operator, placement, nothrow, arrays, etc... My books cover the topic, I've found FAQs on the web that cover the topic, and so on, but all the sources I've found are disjointed. There's a bit on this page, a bit on that page, and so on. The...
15
4667
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 field to start. If I edit that field and then click on the new record button in the navigation buttons, the form goes to a new record and each field has the default value of the previous record. If I put the focus in any field to start, edit that...
7
2479
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 each with a couple of controls in them I then rebuilt my project and my new panels and all controls they contained are gone... I've looked through the Auto generated code but don't see anything that looks wrong Any body have any idea why this...
3
1892
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
9572
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10562
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10319
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10070
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5639
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2978
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.