Wednesday, September 07, 2005

Python note: make use of built-in space

This is about the ways to make (cross module) global variables.

One way of sharing variables among runtime modules is defining a global module, and let every module import it. The global module will be loaded only once, because Python puts every loaded module into sys.modules and makes sure that it won't be executed again by import statements. Once the global module is loaded, every module could access for variables. In this way the variables are shared as global.

The above method takes use of Python module loading mechanism to achieve global sharing. There is a more straightforward way. In Python, searching for variables follows the order of function -> module -> built-in scope. While the variable is not found anywhere in the module, the built-in scope will be looked for. This scope is defined as a global module (or dict).

Suppose we have main module:

g_nConfig = "blabla"
__builtins__.g_nConfig = g_nConfig

import first_module
import second_module

# other things to do

Then in the subsequent executions within the two imported modules, g_nConfig is accessible.

Now, suppose that there are many such global things to use. You can make a concentrated sharing for them. The easiest form could be a dict.

g_dGlobals = {'g_nConfig' : "bla bla", 'g_oObject1' : object1}

Of course, to make the global powerful, you can make it a class.