Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind event to variable in Python

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!

like image 914
dberenguer Avatar asked Jan 25 '26 07:01

dberenguer


2 Answers

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
    # ...
like image 167
jfs Avatar answered Jan 27 '26 20:01

jfs


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.

like image 32
kindall Avatar answered Jan 27 '26 21:01

kindall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!