any trick to allow anonymous code blocks in python?

Doug Holton insert at spam.here
Sat Jun 26 00:30:59 EDT 2004


John Roth wrote:
>>Is there any metaclass trick or something similar to allow anonymous
>>code blocks?
>>
...
> No. If you're looking for GUI callbacks, there's a significant
> gap between lambdas and bound methods. You could
> use something like (not tested):
> 
> b.OnClick = (lambda : sys.stdout("You clicked me"))

Yeah, I didn't mention the lambda option.  I was thinking about 
designing a framework meant for beginners, and I'd rather stay away from 
lambdas.  I'm surprised no one is even proposing support for anonymous 
code blocks in Python that support multiple lines, similar to what Ruby, 
Java, and other languages have.

> If you're doing anything other than a toy program, though,
> the best approach is to wrap the GUI widget in a class,
> and use a bound method of that class for the callbacks.

Right, that is the subclass example I mentioned in the original note, 
but I didn't spell it out:
class MyButton(Button):
     def OnClick(self,event):
         print "you clicked me"
b = MyButton()
I already know that will work, and that is what I would use myself, and 
it is more elegant than lambdas.  I was just looking to see if anyone 
had a hack for anonymous code blocks, but thankyou for your help.



More information about the Python-list mailing list