Overloadable Assignment PEP

Drew Moore drew at astro.pas.rochester.edu
Thu Apr 3 17:05:26 CEST 2003

"Anders J. Munch" <andersjm at dancontrol.dk> wrote in message news:<3e8c083b$0$10386$edfadb0f at dread11.news.tele.dk>...
> "Drew Moore" <drew at astro.pas.rochester.edu> wrote:
> > Howdy! 
> > 
> > I submitted a pre-PEP on overloadable assignment. 
> > 
> > The idea is:
> > 
> > In situations where the assignment token "=" appears, and an augmented
> > assignment symbol (such as +=, -=, *=, etc..) would also be
> > syntactically correct, the assigned-to object would be checked for an
> > __assign__(self, other) method. 
> You terminology is off.  There is no such thing as an "assigned-to"
> object in Python.  Assignments change bindings, not objects.

Right, the binding of the name always changes. When an augmented
assignment operator is overloaded, the method must return a
reference to an object, and this returned reference is bound to the
name on the left hand side. Typical code inspects the "other" object,
modifies self appropriately, and returns a reference to self.
Regular assignment is just the trivial case of augmented assignment.

Seems to me a += b -> __iadd__(a,b)
is very similar a = b -> __assign__(a,b)

the __assign__ method returns a reference, just like __iadd__
this reference will be bound to the name on the left hand side.

> Take a step back and tell us what problem you are trying to solve.
> Whatever it is, I'm sure we can think of a better solution than having
> assignment depend on whatever object, if any, happened to be
> previously bound to the same name.
> python-is-not-c++-ly y'rs, Anders

my original need?
I wanted to create an object that controls a voltage and
use it at the python command line.
by overloading operators, I can do:

voltage += 5  # (raise the voltage by 5 volts)
voltage *= 2  # (double the current voltage)

but when I do 

voltage = 3  # (set the voltage to 3 volts)

my voltage object is clobbered with an integer object.
I don't want to require the user to type any more than
name = value # no name.val = newval, no name.setval(value)

Overloadable augmented assignment provides a  nice framework that
always rebinds the name, but gives the "about to be rebound" name
some say in how this takes place. I'm at a loss to explain why
the "most trivial case of augmented assignment" was denied this power.

Thanks for responding.. Maybe posting on April 1st was a mistake,
people might have thought I was joking around!!

More information about the Python-list mailing list