when reading python documentation and various mailing lists I always read what looks a little bit like a dogma. Global variables should be avoided like hell, they are poor design ... OK, why not ? But there are some real lifes situation where I do not how to avoid such a pattern.
Say that I have a GUI from which several files can be loaded from the main menu.
The file objects corresponding to the loaded files may be used througout all the GUI (e.g. an image viewer that will display an image and on which various actions can be performed on via different dialogs/plugins).
Is there something really wrong with building the following design:
- Menu.py --> the file will be loaded from here
- Main.py --> the loaded file objects can be used here
- Dialog1.py --> or here
- Dialog2.py --> or there
- Dialog3.py --> or there
- ...
- Globals.py
where Globals.py will store a dictionary whose key are the name of the loaded files and the value the corresponding file objects. Then, from there, the various part of the code that needs those data would access it via weak references.
Sorry if my question looks (or is) stupid, but do you see any elegant or global-free alternatives ? One way would be to encapsulate the loaded data dictionary in the main application class of Main.py by considering it as the central access part of the GUI. However, that would also bring some complications as this class should be easily accessible from all the dialogs that needs the data even if they are necesseraly direct children of it.
thank a lot for your help
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…