How to pass a global variable to a module?
wuwei23 at gmail.com
Wed Sep 30 02:24:42 CEST 2009
Mars creature <jin... at gmail.com> wrote:
> Assume that I have 10 parameters need to pass to the function. If
> these parameters are fixed, I can use another module to store these 10
> parameters, and import to the module, as suggested by jean-michel. But
> what if these 10 parameters will be changed in the main program?
With Python, for the duration of program execution a module is
(generally) only ever imported by an import statement once. Any other
imports will instead look up the result of the first import, and will
refer to that module.
So you can use modules to stash variables for the life of the program:
globals.a = 1
globals.b = 2
globals.b = 77
print globals.a, globals.b # will be '1, 77'
> Passing the variable to the function as a parameter suggested by Rami
> will certainly do, but I am wondering weather there are other ways.
> What you'd like to code it?
While you can use globals to avoid having to pass functions around,
it's generally a sign of bad code. You're tightly binding the
behaviour of the function to the presence of the globals, which makes
the function a lot harder to re-use elsewhere.
Depending on the functions, I'd tend to use either a list or a dict:
>>> def positional_args_func(a, b, c, d, e):
>>> params = [1, 3, 5, 7, 9]
>>> positional_args_func(*params) # the * unpacks the list
>>> def keyword_args_func(a=None, b=None, c=None, d=None, e=None):
>>> params = dict(a=1, b=3, c=5, d=7, e=9)
>>> keyword_args_func(**params) # the ** unpacks the dict
If you're using Python 2.6/3.x, you might find namedtuple handy:
>>> from collections import namedtuple
>>> Parameters = namedtuple('Parameters', 'a b c d e')
>>> params = Parameters(1, 3, 5, 7, 9)
Parameters(a=1, b=3, c=5, d=7, e=9)
>>> params.a, params.e
>>> def singular_arg_func(params):
... # access through params.a, params.b etc
Or course, any combination of these can be used in the same functions.
Hope this helps.
More information about the Python-list