1

Consider an object of a class: c = C(). c is imported in multiple parts of my program. During runtime, database operations happen that modify an attribute x of c (c.x = y) in one script, but other scripts are running simultaneously and I want them to load the change immediately. How can I "reload" c in memory everywhere it is used without having to rerun the scripts that use it?

I have read this:

python refresh/reload

And it recommends using the python reload() function to reload the module in memory. It would be great if I could tell every file that imports c to reload it, but only to do so when c.x is modified. How can I do this? I know that if we do:

c = C()
print(c.x)
c.x = y
print(c.x)

then the change will be reflected immediately, but this is within the same script. I have other scripts running simultaneously and I want the same thing to happen to the instances of c in those other scripts.

user11629
  • 109
  • 5
  • Maybe a singleton can be useful in this case, https://en.wikipedia.org/wiki/Singleton_pattern, https://stackoverflow.com/questions/14600075/when-to-use-a-singleton-in-python, – Iván May 26 '23 at 02:24
  • Are all of these "multiple scripts" running concurrently in the same process or different processes? If within the same process data within a module is global so it's automatically shared. If they are different processes just retrieve a fresh copy from the database by instantiating a new copy of `C()` whenever each of these scripts, rather than using `c` repeatedly which will become stale. – metatoaster May 26 '23 at 04:46
  • @metatoaster They're running in different processes i.e. different python interpreter instances. Retrieving a fresh copy of the class when running each script doesn't fix the problem - the database modifies the class during runtime, but how do we tell the other scripts to reload the class/object in memory when it's changed, WITHOUT rerunning those scripts? – user11629 May 26 '23 at 14:28
  • I mean, the class need to refresh with whatever changes made to the database upon creation of new instances of it - the instance of the class should contain the latest changes - the existing design you got now is pretty difficult if not impossible to work with your actual requirements. – metatoaster May 26 '23 at 23:29

0 Answers0