4

Is there some way to call a function each-time the value of a variable changes, in python?

Something like a listener, perhaps?

Specifically, I'm referring to the case where only the variable is shared between scripts like a GAE-Session. (Which uses Cookies, Memcache, etc to share data)

Example: ScriptA & ScriptB, share a session variable. When Script B changes it, SctiptA has to call a method to handle that change.

1
  • 1
    When you talk about 'Script A' and 'Script B', are you expecting communication between handlers for different requests? This isn't possible - one app may be running on multiple, distinct, servers. Commented Sep 26, 2011 at 3:33

4 Answers 4

6

Use properties. Only mutable values can change to begin with.

class Something(object):
    @property
    def some_value(self):
        return self._actual
    @some_value.setter
    def some_value(self, value):
        print ("some_value changed to", value)
        self._actual = value
Sign up to request clarification or add additional context in comments.

1 Comment

I didn't know you could define writable properties like this in Python. I'm not sure if I like it or not, but at least it's novel.
3

If the variable is a class attribute, you may define __setattr__ in the class.

2 Comments

Looks very promising, but I don't control the sessions class. But if there were some way that the method could be declared dynamically (like JavaScript) or something, then it might work...
Can you subclass the 'sessions class' and pass around an instance of the subclass? The subclass would work exactly like the base class, but would have your extra features added in.
0

You Probably need extend type "int" or "float", and override the function "setattr", make it to response in your own way.

class MyInt(int):
    ...
    def __setattr__(self, attr, val):
        ...
        super(MyInt, self).__setattr__(attr, val)
        ...

var = MyInt(5)

Comments

-1

For this case (And I can't believe im saying the words) sounds like situation for setters

def set_myvar(x):
    my_var = x
    some_function()
    return my_var

4 Comments

Nice, but in my case, sadly the function can't be shared as its GAE-sessions I'm talking about.
Then just call the function after the variable change
I was hoping for another way... Especially 'cos both the scripts, sharing the variable don't necessarily share the function.
They would need to share the function for the variable to call the function when its updated

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.