persistant gloabl vars (very newbie) ?

Piet van Oostrum piet at cs.uu.nl
Wed Dec 27 13:06:30 EST 2006


>>>>> "Erik Johnson" <ej at wellkeeper dot com> (EJ) wrote:

>EJ> But briefly, probably what you want to do is put some code in a file, say
>EJ> init.py:

>EJ>     # init.py
>EJ>     X = 3
>EJ>     Y = 5
>EJ>     # A bunch of other stuff


>EJ> And then in your main program, execute

>EJ>     from init import *

>EJ> That will take all the module-scoped variables defined in init.py and place
>EJ> them in the namespace of the import statement (whcih could be global, the
>EJ> interactive interpreter, or otherwise)

This way of saying it is slightly wrong or misleading. It does not place
the global variables of init.py in the importing module in the same way
as most other programming languages use this concept. Rather it makes new
bindings in the importing module with the same names and the same values
as in the original module. So they are new variables with the same values.
If in the importing module e.g. you say X = 4, this will change the value
of X in the importing module, but not in the init module, nor in any
other module that has done 'from init import *'.

If you want that kind of behaviour it is better to use: 'import init' and
refer to the variables as init.X and init.Y so that you can change them.
Whether that is a good idea is another matter.

There are other reasons for not using the from init import * form, as you
might overwrite bindings in the module in an unforseen way. from init
import X,Y explicitely is probably safer. And, by the way, from init import
* can only be used at module level, not in inner namespaces.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list