Person McDood
Person McDood

Reputation: 11

How do I make an if statement trigger whenever I change a variable (Python3)

I'm trying to make a simple little program in python 3 where i have constant statements that will activate further in the code whenever a variable is changed so that i don't have to mess with decisions. For example:

example = 0
if example == 1:
    print("Successful")
example = 1

but it does not update, I'm not sure if 'if' is the best statement for this, but I don't know what else i could use. I tried while but it also did not work. If you could point me in the correct direction that would be great.

Upvotes: 1

Views: 131

Answers (2)

orabis
orabis

Reputation: 2809

It is not possible with primitive types. It can be done through defining an object, and using descriptors. Using the observer design pattern, you can determine the rules you need to trigger a callback event.

In the example below, ObservableVar enables binding to property changes. So, changes in the "example" attribute will trigger callbacks to the binding rules you defined.

class ObservableVar:
    def __init__(self):
        self._example = 0
        self._observers = []

    def __setattr__(self, name, value):
        if name == 'example':
            print("Example changed!")
            for callback in self._observers:
                callback(value)            
        super(ObservableVar, self).__setattr__(name, value)

    def bind(self, callback):
        self._observers.append(callback)

    @property
    def example(self):
        return self._example

    @example.setter
    def example(self, value):
        self._example = value


def callback_rule(example):
    if example == 1:
        print("Successful")    

var = ObservableVar()
var.bind(callback_rule)

var.example = 1

Upvotes: 0

John La Rooy
John La Rooy

Reputation: 304137

You can't do it that way. Here is an example of how you can use descriptors to achieve something similar:

class Foo:
    def __init__(self):
        self._example = 0

    @property
    def example(self):
        return self._example

    @example.setter
    def example(self, value):
        if value == 1:
            print("Successful")
        self._example = value


f = Foo()
f.example = 1

Let me warn you not to get too carried away with this pattern though. It's a good way to end up with hard to debug code.

Upvotes: 3

Related Questions