Python (4) global variable

  • 273
  • 0

global variable

If I create a global variable in one function, here is the way how to use that variable in another function. You can use a global variable in other functions by declaring it as global in each function that assigns to it:
with keyword global

>>> globvar = 0

>>> def set_globvar_to_one():
...     global globvar     # Need to modify global copy of globvar
...     globvar = 1
...     print globvar

>>> def print_globvar():
...     print(globvar)     # No need for global declaration to read value of globvar

>>> print_globvar()
0
>>> set_globvar_to_one()
1
>>> print_globvar()
1

without global

>>> globvar = 0

>>> def set_globvar_to_one():
...     globvar = 42
...     print globvar

>>> def print_globvar():
...     print(globvar)     # No need for global declaration to read value of globvar

>>> print_globvar()
0
>>> set_globvar_to_one()
42
>>> print_globvar()
0

Or just useid(globvar) to check the difference

share global variables across modules

The canonical way to share information across modules within a single program is to create a special configuration module (often called config or cfg). Just import the configuration module in all modules of your application; the module then becomes available as a global name. Because there is only one instance of each module, any changes made to the module object get reflected everywhere. For example:

# File: config.py
​x = 0   # Default value of the 'x' configuration setting
# File: mod.py
​import config
config.x = 1
File: main.py

import config
import mod
print config.x

Module variables are also often used to implement the Singleton design pattern, for the same reason.

Another example is to clear the cache

>>> cache = {}
>>> def clearcache():
...     """Clear the cache entirely."""
...     global cache
...     cache = {}