0

I tried importing that dictionary into all the modules ,but changes made by each module to that dictionary is not reflected in other modules,

How can I maintain a common dictionary so that all the modules access it

file2.py

from collections import *
   database=defaultdict(dict)
   if __name__=="__main__":
     print database[1]["plug"]

file1.py

 from file2 import database
 database[1]["plug"]="xyz"
 print database[1]["plug"]

i tried executing file1.py and then ran file2 it shows keyerror:no plug is found. all the changes made in file1.py are lost

  • @MaskedMan: who says they need to persist the data? – Martijn Pieters Aug 07 '16 at 15:20
  • Sharing a mutable object between modules is trivial; you must be making a mistake somewhere (probably re-binding the name instead of mutating the dictionary in-place). Without code, we can't tell you what you do wrong however. – Martijn Pieters Aug 07 '16 at 15:23
  • I think what you want is a class shared between all your modules for example: `class Test: sharedDict = {'a': 1, 'b': 2}` – Masked Man Aug 07 '16 at 15:26
  • Declare dict in 'demo.py' and import in every module file – Dinesh Pundkar Aug 07 '16 at 15:28
  • i tried importing into all the modules but changes made in a module are not reflected in other modules – SaiVamshi Dobbali Aug 07 '16 at 15:39
  • @SaiVamshiDobbali: you are not running the code at the same time? Then yes, you *do* need to save the dictionary to a file first. The contents of a dictionary are not saved automatically when Python exits. `database=defaultdict(dict)` produces an *empty* dictionary each time you run the module. – Martijn Pieters Aug 07 '16 at 15:41
  • @MaskedMan it is same as sharing a dictionary across all the modules i tried it ,its not working – SaiVamshi Dobbali Aug 07 '16 at 15:41
  • @MartijnPieters,can using threads solve my problem?am new to python i have no idea of it so asking – SaiVamshi Dobbali Aug 07 '16 at 15:43
  • @SaiVamshiDobbali: uhm. No. Threads would not solve your problem. You are expecting volatile data to remain in memory each time you start the Python interpreter. It doesn't. I've duped you to a question that tells you how to save the data to disk instead. – Martijn Pieters Aug 07 '16 at 15:46
  • I first commented about it but as Martjin replied I doubted, anyway I think if your modules are independent and aren't running the same time you should make a module common to them as a proxy and make that module write its dictionary to a file for future uses. – Masked Man Aug 07 '16 at 15:48

0 Answers0