Overloadable Assignment PEP

Drew Moore drew at astro.pas.rochester.edu
Tue Apr 1 23:11:36 EST 2003


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. If this __assign__ method existed, it
would be called, and the reference that it returned would be used for
the assignment.. otherwise, assignment would proceed as it currently
does now.

Thus, a few simple cases:

# do-nothing assign method...
  def __assign__(self,other) :
      return other    #  same as current implementation. 

# "un-writeable" object.. kinda 'const-ish'
  def __assign__(self,other) :
      return self     #  ignore attempt at assignment.. 

and a slightly more complex one:

  def __assign__(self,other) :
      self.value = int(other)
      self.notify() # do the other things needed when value changes
      return self  # and of course, don't lose identity.

David Goodger suggested I search on "__assign__", as this topic has
been discussed before. Well, I did the search, but I did not find a
thread that had quite the same slant on this topic as I have. In any
event, I want to champion this PEP, either to bring it to fruition, or
definitively explain why it won't work.

Most people who proposed this before had the "__assign__" operator as
a method of the "assigned-from" object, not the "assigned-to" object.
I agree.. that does not make sense.. but in the context of augmented
assignment, it seems sensible. (one person did briefly propose
something akin to this approach, but nobody seemed to take notice..)

The situations I can think of where an = assignment is syntactically
correct, but the augmented assignments are not:

1:
multiple assignment..
a = b = 4  # a = b += 4 does not work...

2:
tuple unpacking
a,b,c = 1,2,3  # a,b,c += 1,2,3 does not either.

Why the augmented assingment operators are syntactically incorrect in
these cases is another issue that I'd rather defer discussion on.. I
think probably  it is simpler to consider allowing overloading the
assignment operator in the same situations that the augmented
assignment operators allow overloading.. Just more consistent..

Anyway, That's the gist of it.
(Any insights into how to hack the "ceval" source to implement this
would be appreciated. Insights into why the idea won't work are
equally welcome; I figured I gain that insight by trying to implement
it, too..)

Drew




More information about the Python-list mailing list