global and import

Greg Ewing greg.ewing at compaq.com
Wed Jul 28 19:28:17 EDT 1999


Nathan Clegg wrote:
> 
> I would like to move some of the functions to separate
> modules for several reasons, but need to maintain just the two global
> variables between them.  Can this be done?

Yes, but you have to be careful how you refer to the
global variables from other modules. Always import
the name of the module and use modulename.varname --
don't use the "from" form of input. E.g.

# Module Foo
fred = 42

# Module Blarg
import Foo
print Foo.fred
Foo.fred = 17
print Foo.fred

Note that this will NOT work:
# Module Blarg
from Foo import fred
fred = 42 # BAD

That will create a new variable called fred in
module Blarg and assign to that, not the one
in Foo.

A safer way to deal with variables in other modules
is not to munge them directly, but to import accessor
functions, e.g.

# Module Foo
def get_fred():
  return fred

def set_fred(x):
  global fred
  fred = x

# Module Blarg
from Foo import get_fred, set_fred
print get_fred()
set_fred(17)
print get_fred()

Encapsulating access to globals in this way makes
your code more flexible. You can change your mind
about which module fred is in, or even whether it's
a module level variable or kept somewhere else,
without having to track down all the explicit
references to Foo that you would have scattered
about otherwise.

Greg




More information about the Python-list mailing list