Search code examples
python-3.xglobal-variablespython-multithreading

Accessing a variable from a second module that run on a loop


The y.py script runs continuously and updates the z variable. I need to access the z variable through x.py, and it does not work. I am trying to use two different threads.

y.py

import threading

# Run every 3 seconds to update the z variable
if __name__ == "__main__": # Should avoid the importation to modify the z variable content

    delay = 3
    z = 0

    def foo():
        global z
        z = z + 1
        print("inner",z)
        # This thread run continuously and should not 
        # block the other threads
        threading.Timer(delay,foo).start()  

    foo()
    print("outer",z + 10)

x.py

import y

foo = y.z
print(foo)

Solution

  • You need to change how you are doing things in y.py:

    import threading
    
    # Run every 3 seconds to update the z variable
    delay = 3
    z = 0
    
    def foo():
        global z
        z = z + 1
        print("inner",z)
        # This thread run continuously and should not
        # block the other threads
        threading.Timer(delay,foo).start()
    
    foo()
    print("outer",z + 10)
    
    if __name__ == "__main__": # Should avoid the importation to modify the z variable content
        foo()
    

    if __name__ == "__main__": is driver code Look here for more info

    you should use that to call a function, not nest a function inside of it.

    change x.py to:

    import y
    
    foo = y
    print(foo.z)
    

    output from x.py:

    inner 1
    outer 11
    1
    inner 2
    inner 3
    ...
    

    I have changed your code around a bit to speed it up for my part in answering it so it may not produce your desired output so you may need to change that, but your problem should be fixed.