0

Let's simplify and imagine I have this:

#file a.py
import b

 def register(name, value):
     b.mydict[name] = value


#file b.py    
mydict = {}
print(mydict)


#file c.py
import b
print(b.mydict)

File a.py will register some values using the defined function.

File b.py and c.py will print an empty dictionary.

I know this is really a newbie question but...

How do I make it so that when the function registers it updates mydict in the other files as well?

walkman
  • 478
  • 1
  • 8
  • 21

1 Answers1

1

You just need to import this variable from different files. Here is a full example:

  • file1.py:

    my_dict = {"apple": 1, "banana": 2}
    
  • file2.py:

    from file1 import my_dict
    my_dict["carrot"] = 3
    
  • file3.py:

    from file2 import my_dict
    print(my_dict) #{'apple': 1, 'banana': 2, 'carrot': 3}
    

And here is a screenshot on my machine:

Anwarvic
  • 12,156
  • 4
  • 49
  • 69
  • I can't get this to work either... When I run file2.py if I print my_dict it contains the carrot key when I print file3.py the dictionary is empty again... – walkman May 02 '20 at 14:27
  • 1
    I created a screenshot of this and it's working. Double-check your `import` statements – Anwarvic May 02 '20 at 14:33
  • Can the different behavior be because I'm running this on PyCharm and not in a terminal? – walkman May 02 '20 at 14:49
  • Another question, sorry... Why does file3 import mydict from file2? Can't file2 update the mydict in file1? – walkman May 02 '20 at 14:53
  • 1
    According to your first question, I don't think so... pycharm has nothing to do with internal imports. And according to your second question, if you want the updated version of `my_dict` then import it from `file2`. If you want the original one, then import it from `file1`. – Anwarvic May 02 '20 at 14:56
  • So I can't go back to file1 and expect it to have the updated contents of my_dict right? Also I tested it independently and your code works just fine, guess it's my code that specifically breaks something on your logic. – walkman May 02 '20 at 15:09
  • 1
    yes, if you updated `my_dict` in `file2`. Then `file1` won't have these changes – Anwarvic May 02 '20 at 15:11
  • I'm going to mark your answer as correct, thanks for the time! can I just ask one last thing? Is there anyway for me to have a global variable like one would expect in some other language? – walkman May 02 '20 at 15:14
  • 1
    yeah, check [this](https://stackoverflow.com/questions/13034496/using-global-variables-between-files) out. – Anwarvic May 02 '20 at 15:16
  • 1
    Glad I could help :) – Anwarvic May 02 '20 at 15:23