0

I had asked this question before. capture change of global variable value in python

But there is a small issue. When I extend the str class and apply an observer then a setter method invoke works but when I try to reassign a new value to the same variable name then observer is not called.

How to trigger function on value change?

let's say I have an assignment and reassignment as below:

car = 10
print(10)
car = 20
print(20)

When the variable car is reassigned, any kind of observer is not invoked. Any way I can observe the reassignment or assignment operator. I don't mind working with the AST module. Trace from inspect debugger can slow things up is what I have read

wOxxOm
  • 65,848
  • 11
  • 132
  • 136
Gary
  • 2,293
  • 2
  • 25
  • 47
  • 2
    Not immediately possible as Python did not implement the [descriptor protocol](https://docs.python.org/3/howto/descriptor.html) at the module level by default - in fact the proposal was [rejected](https://www.python.org/dev/peps/pep-0549/) - however, if you are willing to apply the workaround outlined in the linked rejected pep, you can create a property on that `ModuleType` instance to do whatever you need on reassignment. – metatoaster Jan 12 '20 at 11:22
  • An interesting question is whether the language requires an implementation to even *perform* the assignments. `car = 10` has no (other) side effects, and in this example `car` is not otherwise used, so an implementation could simply ignore the two assignment statements without changing the semantics. (You might want to change the example to use `print(car)` to ensure the `car` really gets used.) – chepner Jan 12 '20 at 14:40
  • @chepner Yes&No but true. Issue is in details. Pls have a look at 2ndlink. A comment details these globals or parent scoped can be applied from child scopes or local scopes referencing global scopes. That makes it complicated. Without the ability to trace the assignment value changes, it's practically impossible to iterate on the observer correctly. I saw vyperflow implement, but it's a definite overdo for this use case. I understand ModuleType, will try. Which fn/cls manages these 3 - builtins, = assignment ops, &globals dict? failed finding&dubious impln for docs taking care of it. Any help? – Gary Jan 12 '20 at 17:43
  • 1
    Assignment is a primitive operation; it's not implemented in terms of anything lower. The reason `foo.bar = 3` can be treated specially is because it is *already* syntactic sugar for a method call, `setattr(foo, 'bar', 3)`, rather than a "real" assignment. – chepner Jan 12 '20 at 18:25
  • Ok cool. Thank you chepner for your valuable time. Which classes modify builtins, &globals dict values? – Gary Jan 13 '20 at 00:58

0 Answers0