Newbie: How to touch "global" variables

Heiko Wundram heikowu at ceosg.de
Mon Jul 29 12:28:18 EDT 2002


Hi Jeff!

On Mon, 2002-07-29 at 18:09, Jeff Layton wrote:
>    I want a module to be able to "touch" a variable defined
> globally (from the main script). I don't necessarily want
> to change the value ofthe variable, but to query it. For
> example, get the length. How do I do this?

You mean accessing a variable that is defined in another module? Just
put the variable into the other modules scope by setting it. If you want
to keep the two variables synchronized, use a list. Changing the list in
one module changes the other modules list too.

Example:

----------

main.py:

# Define variable.
x = ["hello"]

# Import submodule and post variable to that scope.
import sub1
sub1.x = x

# Run sub1.print_x()
sub1.print_x()

# Change x.
sub1.change_x()

print x

----------

sub1.py:

def print_x():
  global x # Unnecessary I think...?
  print x

def change_x():
  global x # Unnecessary I think...?
  x[0] = "welcome"

----------

It will happily output (untested... ;p):

["hello"]
["welcome"]

btw. Globals are actually a _nono_ for me! Better pass that parameter to
functions or create a (sort of) module initializing function which you
call from the base module after having imported the submodule, and
passing in the parameter you wish to set (instead of changing namespaces
directly).

And better use classes anyway... ;)

Hope this helps!

	Heiko W.





More information about the Python-list mailing list