473,698 Members | 2,972 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Suggesting for overloading the assign operator

Rim
Hi,

I have been thinking about how to overload the assign operation '='.
In many cases, I wanted to provide users of my packages a natural
interface to the extended built-in types I created for them, but the
assign operator is always forcing them to "type cast" or coerce the
result when they do a simple assign for the purpose of setting the
value of a variable. Borrowing an example from this newgroup, the
second assignment below ereases all Currency knowledge from variable
'c', when the user only wanted to update the value of c, not its type:

c=Currency(5)
c=7

I fully understand the workaround of doing c=Curreny(7) instead, but
users don't want to be bothered with that.

I read some of the prior discussions, but I did not see a suggestion
for permanent a solution. I would like to propose the following.

The idea is to separate the value assignment from the type assignment,
by introducing a new operator, let's say the ':=' operator.

'=' remains what it is, assigns type and value at the same time
':=' assigns only the value

For example:
class myint(int): pass .... a = myint()
a := 6 type(a)
<class '__main__.myint '> a

6

In reality, := would just coerce the return type of the RHS of := to
the type of the variable on the LHS of the :=, preserving the value(s)
as best as it can.

If the type of the variable was still undefined, ':=' would behave
like '='. It might create confusion in future code, but does not break
old code.

I think it would be a nice feature to have. Comments?

Thanks,
- Rim
Jul 18 '05 #1
25 4329

"Rim" <ri*******@yaho o.com> wrote in message
news:6f******** *************** ***@posting.goo gle.com...
Hi,

I have been thinking about how to overload the assign operation '='.


Assignment is a statement, not an operator, and therefore not
overloadable . This is an intentional design decision that GvR will
not change.

TJR
Jul 18 '05 #2

"Rim" <ri*******@yaho o.com> wrote in message
news:6f******** *************** ***@posting.goo gle.com...
Hi,

I have been thinking about how to overload the assign operation '='.
In many cases, I wanted to provide users of my packages a natural
interface to the extended built-in types I created for them, but the
assign operator is always forcing them to "type cast" or coerce the
result when they do a simple assign for the purpose of setting the
value of a variable.


Use a property. Changing the semantics of the assignment
statement (NOT assignment operator) is not going to happen.

Properties are new in Python 2.2 (which is around a year
old by now.) They enable you to have getter and setter
methods with an interface that looks like an instance
variable.

John Roth
Jul 18 '05 #3
Rim
"Terry Reedy" <tj*****@udel.e du> wrote in message news:<co******* *************@c omcast.com>...
"Rim" <ri*******@yaho o.com> wrote in message
news:6f******** *************** ***@posting.goo gle.com...
Hi,

I have been thinking about how to overload the assign operation '='.


Assignment is a statement, not an operator, and therefore not
overloadable . This is an intentional design decision that GvR will
not change.


Well, what about the idea of providing another statement, the one I
proposed in the original post?

'=' statement assigns type and value
':=' statement assigns value only

Rim
Jul 18 '05 #4
Rim wrote:
What do you think about providing a statement to assign values
without assigning type?

'=' statement assigns value and type
':=' statement assigns value ony


I think the concept has some merit. I think that sometimes it useful to ensure
that the target of a rebind operation have the same type as the object which was
bound before the rebind.

I know that the same effect can be achieved by descriptors or overriding
"setattr" et al. Or something like this

a = 9
b = 42
if isinstance(b, type(a)):
a = b
else:
raise TypeError("Inco mpatible types.")

However, these options, i.e. putting type checking logic in "setattr" et al, do
not make it explicit in the code that type enforcement is in place.

Expressing the enforcement syntactically, as Rim suggests, would make it more
explicit for the programmer, as well as providing some extremely useful
optimisation hints, especially for products such as psyco.

Psyco, if I understand it correctly, generates machine code for all paths
through a suite, depending on the types of the objects manipulated in the suite.
Such explicitly stated type enforcement would provide valuable information to
optimisers.

Not that I'm proposing that the OPs solution be adopted. Just that I think he is
addressing a valid concern.

regards,

--
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan: http://xhaus.com/mailto/alan
Jul 18 '05 #5
In article <6f************ **************@ posting.google. com>,
Rim <ri*******@yaho o.com> wrote:

I have been thinking about how to overload the assign operation '='.
In many cases, I wanted to provide users of my packages a natural
interface to the extended built-in types I created for them, but the
assign operator is always forcing them to "type cast" or coerce the
result when they do a simple assign for the purpose of setting the
value of a variable. Borrowing an example from this newgroup, the
second assignment below ereases all Currency knowledge from variable
'c', when the user only wanted to update the value of c, not its type:

c=Currency(5 )
c=7

I fully understand the workaround of doing c=Curreny(7) instead, but
users don't want to be bothered with that.


If you have users who don't want to learn Python, give them a special
Python-like language. I won't say it's trivial, but it's not that hard.
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Usenet is not a democracy. It is a weird cross between an anarchy and a
dictatorship.
Jul 18 '05 #6
Quoth Rim:
[...]
The idea is to separate the value assignment from the type assignment,
by introducing a new operator, let's say the ':=' operator.

'=' remains what it is, assigns type and value at the same time
':=' assigns only the value
That's a peculiar way of speaking. '=' does not assign type and
value to a variable; it assigns an object to a name.

[...] In reality, := would just coerce the return type of the RHS of := to
the type of the variable on the LHS of the :=, preserving the value(s)
as best as it can.
"The type of the variable" is not a meaningful phrase in Python:
names do not have types; objects do. I assume you meant "the type
of the object the name on the lhs is presently bound to".

Coerce how? Do you want a new __magicmethod__ for this operation?

Would ':=' mutate the object presently bound to the lhs name
create a new object and rebind the lhs name? To be concrete:

a = whatever
b = a
a := 7
assert a is b

Should that assertion succeed or fail, in general? (Note that it
fails in general if the ':=' is replaced with '=', even if
whatever == 7.)

Would ':=' support chaining? That is, would
a := b := <some expression>
work? If so, would it be equivalent to
_tmp = <some expression>
a := _tmp
b := _tmp
(except for the namespace pollution), to match the semantics of
chained '='? (Note that the assignments happen left to right.)

Would use of a name on the lhs of a ':=' cause that name to be
considered local, as such use with '=' does?
If the type of the variable was still undefined, ':=' would behave
like '='. It might create confusion in future code, but does not break
old code.
Yikes. Why not raise NameError if the name on the lhs of ':=' is
not yet bound?
I think it would be a nice feature to have. Comments?


Your example
a = Currency(6)
a := 7
is highly strange. (Even if we ignore the question of *which*
currency is being represented; the example could easily be
restated with, say, FixedPoint or Rational or some such.)

How is it that your users are happy to write Currency(...) when
first assigning to a name, but not happy doing so when assigning
later?

Do they not understand that '=' binds a name to an object? Are
they C programmers who think of assignment as copying a value from
one location in memory to another? Do they think of the first
assignment as a type declaration for the name? (If any of these
three are true, they need to be better educated -- they're all
fundamental misconceptions about Python.)

Do they need a language with syntactic support for Currency
objects?

--
Steven Taschuk st******@telusp lanet.net
"Our analysis begins with two outrageous benchmarks."
-- "Implementa tion strategies for continuations", Clinger et al.

Jul 18 '05 #7

"John Roth" <jo******@ameri tech.net> wrote in message
news:vg******** ****@news.super news.com...

"Rim" <ri*******@yaho o.com> wrote in message
news:6f******** *************** ***@posting.goo gle.com...
Hi,

I have been thinking about how to overload the assign operation '='.
In many cases, I wanted to provide users of my packages a natural
interface to the extended built-in types I created for them, but the
assign operator is always forcing them to "type cast" or coerce the
result when they do a simple assign for the purpose of setting the
value of a variable.
Use a property. Changing the semantics of the assignment
statement (NOT assignment operator) is not going to happen.

Properties are new in Python 2.2 (which is around a year
old by now.) They enable you to have getter and setter
methods with an interface that looks like an instance
variable.

John Roth


I usually don't reply to my own posts, but I thought it
might be nice if I put up a skeletal example of how to do it.

I'm assuming that what you want is a way of insuring, in a
class named Foo, that the variable fooBar is always bound
to a class instance of Bar, regardless of what the user tries
to assign to it.

Most of what follows is documented in "What's New in Python 2.2,"
section 2: Peps 252 and 253: Type and Class Changes.

The information on the __new__ method is in the document
under 2.5: Related Links.

The way to do this is:

1. Both Foo and Bar have to inherit from a built-in type.
That's usually "object", but it can be any built-in type.

2. Refactor Foo so that all references to self.fooBar
now refer to self._fooBar. (It can be any name; the
underscore is a convention that means "private."

3. Insert the following code in Foo:

def _getFooBar(self ):
return self._fooBar

def _setFooBar(self , parm):
self._fooBar = Bar(parm)

_fooBar = property(_setFo oBar, _getFoobar, None, "doc strings swing")

4. In class Bar, use the __new__ method to check if
the parameter is an instance of class Bar. If it is, return that
instance, otherwise call your superclass's __new__ method
to create a new object and return it.

5. In class Bar, do whatever type determination you need to
in the __init__ method to build your new Bar object.

Most of this is documented in "What's New in Python 2.2,"
section 2: Peps 252 and 253: Type and Class Changes.

The information on the __new__ method is in the document
under 2.5: Related Links.

HTH

John Roth

Jul 18 '05 #8
On Mon, 2003-06-30 at 20:31, Rim wrote:
The idea is to separate the value assignment from the type assignment,
by introducing a new operator, let's say the ':=' operator.

'=' remains what it is, assigns type and value at the same time
':=' assigns only the value


On the surface, this idea seems appealing. However, besides the
arguments that others have forwarded, you might consider the fact that
given two similar "assignment operators", subtle bugs are bound to
arise.
class myint(int): pass ... a = myint()
a := 6 type(a)
<class '__main__.myint '> a

6


What if the programmer accidentally uses '=' rather than ':=' (and I
think this would be a natural mistake)? It would be legal Python but
would probably not have the intended effect. It is not unlike the
"allow assignment in expressions" arguments that come up here every 3.2
weeks.

Anyway, your arguments cancel themselves out. You asked initially for a
way to overload '=' because your users didn't want to have to type
something different. But ':=' *is* different, so what are you really
looking for?. Worse, because ':=' isn't *very* different, it makes
mistakes more likely.

In short, I think using a = myint(6) or even a.value = 6 is preferable.
Besides, when I used Pascal (many years ago), I found ':=' to be one of
the most annoying (and most common) things I had to type. Please don't
ask to bring it back.
Regards,

--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 (800) 735-0555
Jul 18 '05 #9
On Tue, 2003-07-01 at 11:01, Alan Kennedy wrote:
Not that I'm proposing that the OPs solution be adopted. Just that I think he is
addressing a valid concern.


I agree that it is a valid concern. I think, however, that other valid
concerns outweigh this one. I suspect you think so as well, otherwise
you would have omitted the first sentence.

Regards,

--
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 (800) 735-0555
Jul 18 '05 #10

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

Similar topics

7
8031
by: Paul Davis | last post by:
I'd like to overload 'comma' to define a concatenation operator for integer-like classes. I've got some first ideas, but I'd appreciate a sanity check. The concatenation operator needs to so something like this: 1) e = (a, b, c, d); // concatenate a,b,c,d into e 2) (a, b, c, d) = e; // get the bits of e into a,b,c, and d For example, in the second case, assume that a,b,c,d represent 2-bit integers, and e represents an 8-bit...
16
3087
by: gorda | last post by:
Hello, I am playing around with operator overloading and inheritence, specifically overloading the + operator in the base class and its derived class. The structure is simple: the base class has two int memebers "dataA", "dataB". The derived class has an additional int member "dataC". I am simply trying to overload the + operator so that 'adding' two objects will sum up the corresponding int members.
6
12535
by: c++newbie | last post by:
Hi all, I try to compile the following classes: main.cpp: #include <algorithm> #include <iostream> #include <fstream> #include <iterator>
3
385
by: md | last post by:
Hi, the following code is working for static objects. ie the statement IntArray x(20); my problem is i want to use this overloading operator for dynamically created objects for example the statement IntArray *x; Please give me some help regarding this ////////////////////////////////////////////////////////////////////////////////////////////////////////// class IntArray
3
3275
by: y-man | last post by:
Hi, I am trying to get an overloaded operator to work inside the class it works on. The situation is something like this: main.cc: #include "object.hh" #include "somefile.hh" object obj, obj2 ;
10
2383
by: looping | last post by:
Hi, for the fun I try operator overloading experiences and I didn't exactly understand how it works. Here is my try: def __pow__(self, value): return self.__add__(value) 6
16
4344
by: EM.Bateman | last post by:
Working on Visual Studio .Net I've implemented a class: #ifndef CONTRIBUTOR_H #define CONTRIBUTOR_H enum Gender {male=1, female, unk}; #include <iostream> #include <iomanip> #include <string>
3
1889
by: Philipp Brune | last post by:
Hi all, i just played around a little with the c# operator overloading features and an idea came to my mind. You all possibly know the Nullable<T> Datatype. Now i thought it would be a nice idea to write my own Revertable<Ttype that maintains the values of multiple assignments and can revert to a previous value. An Example to make it clear : Revertable<intir0 = 123; ir0 = 500;
1
1744
by: fabian.lim | last post by:
Hi all, Im having a problem with my code. Im programming a vector class, and am trying to overload the () operator in 2 different situations. The first situation is to assign values, e.g. Y = X(1,2), the elements 1 and 2 of X gets assigned to Y. In this case, the operator () overload should create a copy that is unmodifiable. In the 2nd case, I want do assign values to elements 1 and 2, e.g. X(1,2) = Y. Then in this case, the values...
0
8683
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9170
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
9031
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...
1
8904
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7741
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
6531
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
4372
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4624
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2341
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.