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 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
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
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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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
|
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...
|
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...
|
by: Razvan |
last post by:
Hi !
Is there any difference between new X and new X() ?!
Regards,
Razvan
|
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
| |
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...
|
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...
|
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...
|
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...
|
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));
|
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,...
| |
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...
|
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...
|
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...
|
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...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |