Reputation: 49
I am relatively new to python and I have a simple python module with some constants which are being modified by some code in other files. I want these to be the same through out. i.e
a.py
start = True
b.py
import a
while(a.start):
//do something
c.py
import a
a.start =False
My understanding of a python module is, it acts like a singleton and any module is imported only once. So, when I try running b.py
and then run c.py
, what I am expecting would be this:
b.py
loopsc.py
sets start to falseb.py
stops looping as they are importing from the same moduleBut, when I run this I think what is happening is module is being re-imported as a duplicate and by b.py
never stops running. Is there something I am doing something very basic wrong?
Upvotes: 2
Views: 108
Reputation: 155046
As Martijn explained, Python modules are singletons within the same process. To achieve what you are trying to do, you need to implement some form of interprocess communication. To take a trivial example, you could write to a file:
# a.py
import os
REQUEST_FILE = 'stop-request'
def should_stop():
return os.path.exists(REQUEST_FILE)
def clear():
if os.path.exists(REQUEST_FILE):
os.unlink(REQUEST_FILE)
def request_stop():
with open(REQUEST_FILE, 'w'):
pass
# b.py
import a
a.clear() # avoid leftover stop-request stopping us before we've started
while not a.should_stop():
# ... do something ...
# c.py
import a
a.request_stop()
Upvotes: 2
Reputation: 1122342
Python modules are singletons within one run of the interpreter.
Running c.py
in a separate process will not alter the value of start
in another Python interpreter.
Upvotes: 5