Overloadable Assignment PEP

Drew Moore drew at astro.pas.rochester.edu
Sat Apr 5 08:32:14 EST 2003


list-python at ccraig.org (Christopher A. Craig) wrote in message news:<mailman.1049471534.24194.python-list at python.org>...
> drew at astro.pas.rochester.edu (Drew Moore) writes:
> 
> > so far, the response seems to be:
> > "it is technically possible, but my scripts might
> > run slower.. and it just makes me nervous."
> 
> Not might run slower, would run not just slower but a ton slower.
> You're basically replacing the C code
> a=b
> 
> with at least one, and possibly several dict lookups.  Your idea about
> caching the value is a decent one, but you have the problem that class
> dicts are mutable, so what if someone does
> 
> >>> class foo:
> ...  pass
> ...
> >>> t = foo()
> >>> t.__dict__.__assign__ = lambda t, a: t.elem=a
> 
> If __assign__ is allowed, that will be expected to work.
> 
> A bigger problem to me is that '=' currently means rebinding names.
> If I see 'a=b' in Python, I immediately presume that 'a' doesn't exist
> after the assignment.  If you change this then it will sometimes mean
> rebinding and sometimes mean something else.
> 
> If you want a way to set something's value, I imagine you'll have a
> lot more support for adding an operator rather than making '=' one.
> I'm all for Lulu's suggestion of adding a ':=' operator for that sort
> of situation.

Excellent observation about the multiple dict search, Christopher!

A cached bit would not work if you expected derived classes
to inherit the overload. A base class, if modified, would have
to go to all derived instances and set the bit.

That would definitely not fly! 

The most sensible implementation I can think of:
The __assign__ method belongs to the object.
BUT---
The "use the __assign__ method if present" flag
belongs to the name, and is only set under certain
circumstances.. such as if the name
is bound to a freshly instantiated instance
that has __assign__ method defined.
(got to think about this one some more)

a = myOAclass() # a overloads assignment
b = a # b does not. it has the __assign__ method but..
      # will not use it.
b = c # b has been reassigned!!

f(a) # reference passed to f does not overload assignment!
L[3] = a # list item does not overload assignment

### perhaps the := operator has a place here...
a = myOAclass() # a does not overload assignment..
b := a # but b does..??
# (set the AO flag in b if the := operator is used
# and a has __assign__ method.)

c := myOAclass() # c overloads assignment
d = c # d does not.

Hmm, I like this..

The OA flag sensibly belongs to the name, not the object.
(its really the name that wants this property, not the object.)
Now, performance hit is tiny, because it is just checking a bit.
reassignment does not propogate the bit in the name...
no ripples..

Drew




More information about the Python-list mailing list