Python - problems with shared variable
Question: I'd like to use a shared queue from multiple threads and modules. I have the
following Python code:

    
    
    # moda.py
    
    import queue
    import modb
    
    q = queue.Queue()
    
    def myPut(x):
        q.put(x)
    
    def main():
        print('moda:', str(id(q)))
        modb.go()
        q.get()
    
    
    if __name__ == '__main__':
        main()
    

and

    
    
    # modb.py
    
    import moda
    import threading
    
    
    def something():
        print('modb:', str(id(moda.q)))
        moda.myPut('hi')
    
    
    def go():
        threading.Thread(target = something).start()
    

`something` gets called on thread 1, `somethingElse` gets called on thread 2.
The addresses of `q` are different in these two methods - which is why the
call to `get` never returns. How can I avoid this? Is it because of the cyclic
import or because of multithreading?


Answer: [The link](http://stackoverflow.com/a/744403/222914) posted by Austin Phillips
in the comments has the answer:

> Finally, the executing script runs in a module named __main__, importing the
> script under its own name will create a new module unrelated to __main__.

So, `__main__.q` and `moda.q` (as imported into `modb`) are two different
objects.

One way to make it work is to create a separate main module like this and run
it instead of `moda`:

    
    
    # modmain.py
    
    import moda
    
    if __name__ == '__main__':
        moda.main()
    

However, you should still consider putting `q` and other shared stuff into a
new module that you import into both `moda` and `modb` to avoid some other
pitfalls.

