0

For example, take the code

import numpy as np

np_function = np.add
np.__dict__.update({"add": 10})
print(np.add, np_function)

np.add gives 10, but np_function still points to the original numpy function, since it was assigned before the update of the dictionary. Is there any way for us to update the value of np_function if the value of np.add changes?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
matt
  • 11
  • 1
  • 3
    TL;DR: no. Variables hold references to objects. They have absolutely no way of knowing when a different variable gets bound to a different object. `np_function` will keep referencing the object that was assigned to it until you explicitly bind it to a different object. – Brian61354270 Mar 01 '23 at 17:13
  • @Brian add as an answer. This should be really useful for others in the future. – Blue Robin Mar 01 '23 at 17:16
  • @BlueRobin I'm almost certain this question is a duplicate. If I can't find a good dupe target, then I'll make that an answer – Brian61354270 Mar 01 '23 at 17:18
  • Related/possible duplicates: [Why is a variable not updating after changing its dependent variable?](https://stackoverflow.com/q/62042913/11082165), [Are Python variables pointers? Or else, what are they?](https://stackoverflow.com/q/13530998/11082165), [If two variables point to the same object, why doesn't reassigning one variable affect the other?](https://stackoverflow.com/q/56667280/11082165) – Brian61354270 Mar 01 '23 at 17:20
  • Technically this is possible, but you really shouldn't do this and it probably wouldn't do what you think it does... – MisterMiyagi Mar 01 '23 at 17:27
  • Please [edit] the question to clarify what exactly you need. This can range from "simple" to "difficult" up to "impossible" depending on the fine print. Do you want *all* variables to change when their referent is updated or only specific ones? Do you want this only for specific referents or all of them? Do you want this for module globals or also other kinds of variables (e.g. function locals, class locals, attributes, ...)? – MisterMiyagi Mar 01 '23 at 17:33
  • @MisterMiyagi I'd like it for all referents ideally. I'd say class attributes would be the most common for me if you have a simple solution for that case – matt Mar 01 '23 at 17:55
  • @matt For a class (instances, actually) I'd go directly with properties so that the lookup is performed anew on every access. No need to actually have and update real attributes. – MisterMiyagi Mar 01 '23 at 19:31

0 Answers0