Richard Jones' Log: Something I'm working on...

Fri, 07 Aug 2009
with gui.column():
    text = gui.label('hello!')
    items = gui.selection(['one', 'two', 'three'])
    with gui.button('click me!'):
        def on_click():
            text.value = items.value
            text.foreground = red
Comment by bc on Fri, 07 Aug 2009

OK, now I'm impressed. That's the most unexpected use for contextmanagers I've yet seen. neat.

Comment by Ville on Fri, 07 Aug 2009

How does the gui get a reference to on_click?

Comment by Ville on Fri, 07 Aug 2009

Nevermind - I assume it's harvesting locals()?

Comment by Robert Schultz on Fri, 07 Aug 2009

I don't code Python much, but this looks really interesting :)

Comment by Bill Mill on Fri, 07 Aug 2009

Alright, I'm stumped. How the heck did you get the context manager to find the function defined within?

I've thought it should be simple ever since I saw the spec, and am frustrated that it's not. How hacky is your solution?

Comment by Richard Jones on Fri, 07 Aug 2009

It's just the right amount of hacky :)

Comment by Paul on Sat, 08 Aug 2009

This kind of makes python look a bit like javascript.

except rather than object attributes you are using scope... is that allowed? or will the programming gods smite you?

is on_click a defined function i.e can I do an 'on_mouseover(), on_mousedown(), on_mouseout()?

Comment by bc on Sat, 08 Aug 2009

After thinking about this a bit, I'm unconvinced of it's usefulness. If you translate 'with' -> 'class', you more-or-less have a declarative class definition but without the benefits of python's object/class-model (inheritance, for example).

Comment by Travis on Sun, 09 Aug 2009

This is pretty clean and nice. I've posted a similar short snippet that has it's magic performed by the traits library here.

Comment by ilya n. on Mon, 10 Aug 2009

Istead of:

    with gui.button('click me!'):
        def on_click():
            ...
why not:
    @gui.button('click me!')
    def button():
        ...
Advantages --
  • no deep introspection
  • binds to local variable button
  • call to gui.button()() is similar to gui.label()
  • it's clear there is only one event.

Comment by Richard Jones on Mon, 10 Aug 2009

@ilya, you're reading ahead - the decorator form is already coded :)

As for the event name though ... hmm.