any trick to allow anonymous code blocks in python?

John Roth newsgroups at jhrothjr.com
Fri Jun 25 20:43:03 EDT 2004


"Doug Holton" <insert at spam.here> wrote in message
news:v6GdnWji9PwSMUHdRVn-uw at comcast.com...
> 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"

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"))

which will work (assuming I've got the syntax right).

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.

The example in the Tkinter chapter of the Python Library
Reference (16.1.2.2 in the Python 2.3.3 docs) shows
how to do it. It's amazingly simple, it's completely object
oriented, and it gives you full access to the instance within
the callback.

John Roth





More information about the Python-list mailing list