any trick to allow anonymous code blocks in python?

Peter Otten __peter__ at web.de
Sat Jun 26 05:07:08 EDT 2004


Doug Holton wrote:

> Is there any metaclass trick or something similar to allow anonymous
> code blocks?
> 
> I'd like to be able to let users do something like this fictitious
> example: b = Button()
> b.OnClick =:
>      print "you clicked me"
> 
> But that would require adding a special "=:" operator to bind a code
> block to a function.
> Is there any PEP for something like that?  I see 310 might allow:
> b=Button()
> with b.OnClick:
>      print "you clicked me"
> 
> I know I can already do it like these examples:
> def OnClick(self,event):
>      print "you clicked me"
> b.OnClick = OnClick
> or
> b = Button(OnClick=OnClick)
> or subclassing Button.

Maybe you can use something as simple as a naming convention, i. e.
automatically associate a function b1OnClick() with a button b1:

import types

class Widget:
    pass

class Button(Widget):
    def __init__(self, name):
        self.name = name

def makeMethod(widget, methodname, function):
    setattr(widget, methodname, lambda: function(widget))

def collectMethods():
    ns = globals()
    widgets = []
    functions = []
    for n, i in ns.items():
         if isinstance(i, Widget):
            widgets.append((n, i))
         elif isinstance(i, types.FunctionType):
            functions.append((n, i))

    for fn, f in functions:
        for wn, w in widgets:
            if fn.startswith(wn):
                makeMethod(w, fn[len(wn):], f)
                break

#begin client code
b1 = Button("one")
b2 = Button("two")
b3 = Button("three")

def b1OnClick(self):
    print "you clicked button 1"

def b2OnClick(self):
    print "you clicked button %s" % self.name

b3OnClick = b2OnClick
#end client code

collectMethods()
b1.OnClick()
b2.OnClick()
b3.OnClick()






More information about the Python-list mailing list