How to pass a global variable to a module?

alex23 wuwei23 at gmail.com
Tue Sep 29 20:24:42 EDT 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:

a.py:

    import globals

    globals.a = 1
    globals.b = 2

b.py:

    import globals

    globals.b = 77

c.py:

    import globals

    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):
...     pass
...
>>> 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):
...     pass
...
>>> 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)
>>> params
Parameters(a=1, b=3, c=5, d=7, e=9)
>>> params.a, params.e
(1, 9)

>>> def singular_arg_func(params):
...     # access through params.a, params.b etc
...     pass
...
>>> singular_arg_func(params)
>>>

Or course, any combination of these can be used in the same functions.

Hope this helps.



More information about the Python-list mailing list