A critic of Guido's blog on Python's lambda

David C. Ullrich ullrich at math.okstate.edu
Mon May 8 09:05:38 EDT 2006


On Sun, 07 May 2006 10:36:00 -0400, Ken Tilton <kentilton at gmail.com>
wrote:

>[...]
>
>Your spreadsheet does not have slots ruled by functions, it has one slot 
>for a dictionary where you store names and values/formulas.
>
>Go back to your example and arrange it so a and b are actual slots (data 
>members? fields?) of the spreadsheet class. You can just stuff numbers in a:
>
>    sheet1.a = 42
>
>but b should be somehow associated with a rule when sheet1 is created. 
>As I said in the other post, also associate an on-change callback with 
>slots a and b.

I must be missing something - seems this should be easy using
__setattr__ and __getattr__. Then _literally_ there's just a
dict containing names and functions, but when you _use_ the
class it looks just like the above:

>[...]
>
>When that is done we can look at a working example and see how well 
>Python fared without macros and full-blown lambda.

No lambda in the non-programmer-half-hour implementation below.
You need to define a named function for each cell to use as
a callback. Except for that what are Cells supposed to do that
the implementation below doesn't do?

"""PyCells.py"""

class Cell:

  def __init__(self, name, owner, callback):
    self.name = name
    self.callback = callback
    self.owner = owner

  def onchange(self, value):
    self.value = value
    self.callback(self, value)

class Cells:

  def __init__(self):
    #self.slots = {}
    #Oops, don't work so well with __setattr__:
    self.__dict__['slots'] = {}

  def __setattr__(self, name, value):
    self.slots[name].onchange(value)

  def __getattr__(self, name):
    return self.slots[name].value

  def AddCell(self, name, callback):
    self.slots[name] = Cell(name, self, callback)

***********

Sample use:

cells = Cells()

def acall(cell, value):
  cell.owner.slots['b'].value = value + 1

cells.AddCell('a',acall)

def bcall(cell, value):
  cell.owner.slots['a'].value = value - 1

cells.AddCell('b',bcall)

cells.a = 42
print cells.a, cells.b
cells.b = 24
print cells.a, cells.b

************************

David C. Ullrich



More information about the Python-list mailing list