truly global variables

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Thu Feb 19 10:06:43 CET 2004


On 19 Feb 2004 00:47:13 -0800, ketulp_baroda at yahoo.com wrote:
> I want a variable such that if i change its value in any module then
> it should be reflected in other modules too.

Fortunately, this nightmare is not possible in Python.

What you should be doing is implementing the variable in a module that
is imported wherever that variable is needed.  This allows you more
control over how the variable is handled; you know there is only one
place where the variable is declared, and any usage of the variable is
explicitly preceded by the module name.

One common place where people think they want global variables but
really want a common module, is configuration variables.  Simply make a
single module whose specific purpose is to hold the configuration
variables for your application, then use the config variables via that
module:

    import AppConfig
    open_screen_window( AppConfig.window_size )
    AppConfig.preferred_hostname = None

The next step would be to make an AppConfig class that handles things
like persistence of config changes, but that may be more complexity than
you need.

-- 
 \       "As the most participatory form of mass speech yet developed, |
  `\    the Internet deserves the highest protection from governmental |
_o__)                intrusion."  -- U.S. District Court Judge Dalzell |
Ben Finney <http://bignose.squidly.org/>



More information about the Python-list mailing list