Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid global variables

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

like image 908
Eurydice Avatar asked Apr 15 '13 08:04

Eurydice


1 Answers

Global variables should be avoided because they inhibit code reuse. Multiple widgets/applications can nicely live within the same main loop. This allows you to abstract what you now think of as a single GUI into a library that creates such GUI on request, so that (for instance) a single launcher can launch multiple top-level GUIs sharing the same process.

If you use global variables, this is impossible because multiple GUI instances will trump each other's state.

The alternative to global variables is to associate the needed attributes with a top-level widget, and to create sub-widgets that point to the same top-level widgets. Then, for example, a menu action will use its top-level widget to reach the currently opened file in order to operate on it.

like image 61
user4815162342 Avatar answered Oct 07 '22 18:10

user4815162342