global variables - how??

Johann Hibschman johann at physics.berkeley.edu
Wed Apr 12 16:23:11 EDT 2000


Anders Eggers-Krag writes:

> it is obvious not to use global variables except when the use of
> them is obvious, in my case I could otherwise send them along with
> every function, creating a huge overhead passing a million pointers
> around, using exactly the same amount of memory, or in fact more,
> than I would using globals.

> I did figure out how to do it myself after a lot of trying, but as
> you said it is ugly, but this really anoys me, and I *was* starting
> to like python...

Weird.  Honestly, in years of writing python code, I've never had
a problem with globals, and I'm more than a little curious as to
what you're doing.

If the globals are only needed inside one module, you can simply refer
to them by adding 'global foo' at the beginning of the module, and you
only have to do that if you want to re-bind the variable.  (i.e. not
even if you're modifying a mutable object itself.)

If you need globals across multiple modules, just define a module to
put them in.  i.e. make an empty file, 'gl.py', possibly just
containing a comment:

gl.py:
--------------------------------------------------
"""
Dummy module to contain global variables.
"""
pass
--------------------------------------------------

Then you can just import gl and modify its contents to you heart's
content.

import gl
gl.x = 10
print gl.x
etc.

This is a bit hacky, but it works fine.

If you want to change variables around in the "if
__name__=='__main__'" block, you're best off simply re-importing the
module, then changing things through that.

ie.
t1.py:
------------------------------
import t2
x = 10
if __name__=="__main__":
  import t1     # pull itself into scope, evading the __main__ hackery
  t1.x = 100    # modify the vars properly
  t2.do_stuff() # go from there

Does this help?

--Johann

-- 
Johann Hibschman                           johann at physics.berkeley.edu



More information about the Python-list mailing list