2

Im new to python In python here is my code

Stringtoknow = "value"

#some code

def onchange():
    print("the value change")

Stringtoknow = "new value"

# run the onchange function

I want the code that will run onchange function when Stringtoknow variable changes

Coder-boy
  • 21
  • 1
  • Does this answer your question? [How to watch for a variable change in python without dunder setattr or pdb](https://stackoverflow.com/questions/13402847/how-to-watch-for-a-variable-change-in-python-without-dunder-setattr-or-pdb) – Arya McCarthy Feb 22 '21 at 02:39
  • 3
    This sounds like an [XY problem](https://xyproblem.info/). What are you actually trying to do? – SuperStormer Feb 22 '21 at 02:47

3 Answers3

2

If you can put the variable inside of a class instance, then we can do it.

Instance variables are nice because we have total control over them. We can always control what happens when assigning to them. This is exactly what properties are for.

class Example:

    def __init__(self):
        self._impl = "value"

    @property
    def Stringtoknow(self):
        return self._impl

    @Stringtoknow.setter
    def Stringtoknow(self, v):
        self._impl = v
        print("the value changed")

example = Example()
print(example.Stringtoknow)
example.Stringtoknow = "new value"
print(example.Stringtoknow)
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
0

This doesn't exactly answer your question, but consider using a setter. If you do that, this becomes trivial

Stringtoknow = ''

def update_string_to_know(new_string):
    Stringtoknow = new_string
    print("the value change")

update_string_to_know("new value")

Without more context, this seems like a reasonable way of accomplishing the ask

miversen33
  • 573
  • 5
  • 19
0

Based on Silvio Mayolo's answer, I think comparing origin value with final value is also needed.


class StringValueWatcher():

    def __init__(self):
        self._final = self._origin = 'initial'

    @property
    def string_value(self):
        return self._final

    @string_value.setter
    def string_value(self, v):
        self._origin = self._final
        self._final = v
        if self._origin != self._final:
            self.on_change()

    def on_change(self):
        print(f"value changed from {self._origin} to {self._final}")


e = StringValueWatcher()
print(e.string_value)        # initial value
# initial
e.string_value = "initial"   # not change
e.string_value = "new_value" # changed
# value changed from initial to new_value



jia Jimmy
  • 1,693
  • 2
  • 18
  • 38