简体   繁体   中英

change global variable at runtime for imported function

I am trying to make functions in different files of a larger program send a message to each other. There is a function without a return statement. In a test example, if I do the following in one file, I can change a global variable and detect its change at run time:

one_file.py

import time
import threading
has_run = False

def processing_function():
    global has_run
    time.sleep(5)
    has_run = True

start = time.clock()

thread = threading.Thread(target=processing_function)
thread.start()

while True:
    print(has_run)
    time.sleep(0.5)
    if (10/3600) < time.clock() - start:
        break

When run, this will print False for a while then start printing True.

I tried to get this to work across two files like this:

file1.py

import time
has_run = False

def processing_function():
    global has_run
    time.sleep(5)
    has_run = True

file2.py

from file1 import processing_function, has_run
import time
import threading

start = time.clock()
thread = threading.Thread(target=processing_function)
thread.start()

while True:
    print(has_run)
    time.sleep(0.5)
    if (10/3600) < time.clock() - start:
        break

If you now run file2.py, it only prints False a lot of times.

Why is this imported global variable not being modified by the running process, and how can this be refactored so it works?

When you import the name has_run , you have created a new global in the current module named has_run that refers to the same object as file1.has_run , but an assignment to one of the names does not affect the other. If you want to see the changes made by processing_function , you need to continue accessing the name through the module.

while True:
    print(file1.has_run)
    ...

(This is because processing_function assigns a new value to its global, rather than mutating an existing value.)

You can observe this through a much simpler example. Consider a very simple module tmp1 :

x = 3

Now see how from tmp1 import x creates a global variable whose value remains independent of tmp1.x :

>>> import tmp1
>>> from tmp1 import x
>>> x
3
>>> tmp1.x
3
>>> x = 6
>>> tmp1.x
3
>>> tmp1.x = 5
>>> tmp1.x
5
>>> x
6
>>>

I believe the details of sharing the variable between Threads in Python you can find in this question .

Essentially, sharing any state (incl. variable) between threads requires synchronization (eg using threading.Condition ). Otherwise, you are risking a race condition between one or more threads competing for access to the variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM