Make 'def' and 'class' usable within expressions

Glenn Andreas gandreas at no.reply
Thu Mar 25 17:51:21 EST 2004


In article <mailman.429.1080249113.742.python-list at python.org>,
 Shane Hathaway <shane at zope.com> wrote:

> Glenn Andreas wrote:
> > Also, limiting to "one per expression" prevents you from doing something 
> > like:
> > 
> >    myHandlers = {
> >       "click" : def(x,y):
> >                      print "click at x,y"
> >       "enter" : def():
> >                      print "mouse entered"
> >       "exit"  : def():
> >                      print "mouse exited"
> >    }
> 
> I just thought of a better way to write this.
> 
>      myHandlers = {}
>      myHandlers["click"] = def(x,y):
>          print "click at x,y"
>      myHandlers["enter"] = def():
>          print "mouse entered"
>      myHandlers["exit"] = def():
>          print "mouse exited"
> 
> I think that's pretty nice.

That would work, but suddenly we've got a rule that "dictionaries can 
specify all their keys and values, except only one of which can be an 
'inlined' anonymous function, so if you need more, you need to add the 
rest manually".

Perhaps, if we go with the "foo = def()" being the same as "def foo()":

myHandlers = {}
def myHandlers["click"](x,y):
   print "clicked at x,y"

.. at which point my fingers revolted and refused to type anything 
further example in such stylistic abomination (which is one of the 
reasons I also hate that form of decorators, since it looks like you are 
binding the value of a dictionary).


OTOH, if you look at NewtonScript (which was prototyped based, BTW) you 
would define the methods for an object exactly like one would create any 
old frame (which is pretty much the same as a dictionary, but is also an 
object - there was no difference between the two):

anObject := {
   click: func(x,y)
         Print("click at x,y");
   enter: func()
         Print("mouse entered");
   exit: func()
         Print("mouse exitted");
};

(and in the above, "click", "enter", "exit" are all symbols, which are 
more like Smalltalk symbols than python strings but it was trivial to 
convert between the two)

Still, all of that worked because NewtonScript had statements and 
expressions all handled by the same form of delimination.  In fact, 
statements were expressions, so you could do "min = if x < y then x else 
y;" which mixes expressions (the RHS of the assignment) with the 
if-statement which has expressions for bodies of then & else clauses 
(instead of more complex statements).



More information about the Python-list mailing list