3

Is there any way to bind an event to a variable in Python or wxPython? Something like this:

    self.Bind(EVT_ONCHANGE_VAR, self.mycallback, variable_to_watch)

This would let a dialog to show or hide depending on the value of such variable.

Thanks!

2 Answers 2

3

traits allows you to get notifications when the value is changed.

In your case you could make variable_to_watch a property:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, value):
        self._x = value
        self.show_hide_dialog() # or generate an event in general
    # ...
Sign up to request clarification or add additional context in comments.

2 Comments

traits is quite useful... there was a good traits talk at pycon2010
isn't that rather un-pythonic?
2

If it's an attribute on an instance of a class, this can be done reasonably easily by writing a custom __setattr__() method for the class that sends out a notification when a particular attribute changes. (You can also use a property, but you'd have to make a separate one for each attribute.) For variables, this is much more difficult; Python doesn't have any built-in mechanism for doing this, so you'd have to tie into the trace hook and introspect the variable after each line of code is executed. This will significantly slow down your program, but it can be done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.