[wingide-users] global imports

Paul Du Bois dubois at doublefine.com
Tue Jun 7 12:25:14 MDT 2011


> > # project_main.py
> > import parameter1, parameter2, parameter3
> > import subroutines
> > subroutines.init(parameter1, parameter2, parameter3)

> > # subroutines.py
> > def init(a,b,c):
> >    global ga, gb, gc
> >    ga,gb,gc = a,b,c

> Yup, did that.  No problem in that aspect.  The problem is that items
imported into the
> init routine are local to that routine.  I need them to be global to
the entire
> subroutines module.

I don't see "import" in the init routine, so I don't understand what
"imported into the init routine" means.  Perhaps you mean "passed into
the init routine", but the items passed into the init routine are
explicitly made global to the module.  Or perhaps you mean that you
don't care for the extra level of indirection in the subroutines module;
you want to reference them without prepending "ga."?

> One of us is not understanding the other.
> Virtually EVERY PARAMETER of the code is needed by the subroutines
module.

I don't understand what a "parameter of the code" refers to.  Does it
mean contents of the parameter modules?  They are all accessible through
that extra level of indirection (see last example below).

> # subroutines.py
> def init(module_name)
>     global *
>     import module_name

If you really truly care about not having that extra level of
indirection, try the moral equivalent of this (and careful that you
don't copy too much -- you might want to skip everything with a "__"
prefix)

def init(a, b, c):
  for module in a,b,c:
    globals().update(module.__dict__)

> In the first case I was considering having to put import statements in
each function of
> subroutines.py so that they could gain access to the parameters in
lieu of doing it once
> at the top of the module.

I think you should place less emphasis on using "import"; it's a red
herring.  Once your caller's compiled and loaded the .py file you have
no need for import or __import__ or any of that functionality; trying to
use import otherwise is making you chase down over-complicated
solutions.  For example:

def init(a,b,c):
   global ga, gb, gc
   ga,gb,gc = a,b,c
def do_something():
   # from (some variable module name) import x,y,z       # NO
   x,y,z = ga.x, ga.y, ga.z
   # alternatively, just reference them as ga.x, ga.y, ga.z



More information about the wingide-users mailing list