Bertrand Tan
Bertrand Tan

Reputation: 31

Python dictionary not updated across different files

I have two files

  1. runner.py - main
import secondthread
my_dict = {}

def action1():
    my_dict["i"] = 2

if __name__ == "__main__":
    action1()
    secondthread.action2()
  1. secondthread.py
import runner

def action2():
    try:
        print("Thread2: dict value is = {}".format(runner.my_dict["i"]))
    except Exception as e:
        print("Thread2: dict haven't got updated value, len of dict is: {}".format(len(runner.my_dict)))

I am unsure why despite sequentially running action1 then action2 does not update the dictionary with the new key-value pair.

I have tried setting my_dict as a global variable in secondthread.py and it does not work. I understand that perhaps the circular dependency (runner.py depends on secondthread.py and secondthread.py depends on runner.py may be problematic, but I am not sure how else to read my_dict from secondthread.py).

Update1: I have also tried inside secondthread.py which still results in the same error.

from runner import my_dict

Wouldn't this method already retrieve my_dict from global namespace?

Upvotes: 2

Views: 300

Answers (1)

Jussi Nurminen
Jussi Nurminen

Reputation: 2408

I think the crux of the problem is that due to the circular import, runner gets imported a second time. Importing a module will cause its code to run, thus my_dict will get initialized again, which you don't want. Code that depends on the ordering or frequency of module imports is problematic.

The recommended way to solve this kind of problem is to move the variable initializations to a single module, which is then imported once from each file: https://docs.python.org/3/faq/programming.html#how-do-i-share-global-variables-across-modules In your case, you would create a third file, say init_vars.py and import it from both runner.py and secondthread.py.

Upvotes: 2

Related Questions