Is it just Syntactic Sugar ?

Guido van Rossum guido at python.org
Wed May 31 19:49:57 EDT 2000


I know I shouldn't be posting in this thread, and I won't be there to read
the
responses, but here's what I thought would be cool.

x+=y is syntactic sugar for x=x.__add_ab__(y); the "ab" means "and becomes"
(an old Algol-68 naming convention; we could pick something better later
but this will do for the explanation).

For immutable types, this is defined as

  def __add_ab__(self, other):
      return self+other

For mutable types, this is defined as a self-mutating operation,
e.g. for lists it could be

  def __add_ab__(self, other):
      self.extend(other)
      return self

Thus,

  i = 1
  i += 1

does the right thing (i is set to 2), and

  a = [0]
  b = a
  a += [1,2,3]

modifies the object in place, so that both a and b are [0,1,2,3].

User classes can do whatever their author likes.

A base class can be provided that defines __add_ab__, __sub_ab__ etc.
in terms of self.__add__, self.__sub__, etc.

-- 
--Guido van Rossum (home page: http://www.python.org/~guido/)




More information about the Python-list mailing list