Scoping issue with import

Carl Banks invalidemail at aerojockey.com
Mon Feb 28 19:14:48 EST 2005


James Stroud wrote:
> Say I have a module, we'll call it "my_imported_mod". It contains a
function
> in it that calls another function, "myfun". The "myfun" function is
in the
> module "my_main_mod", that imports "my_imported_mod".

[snip]

> How to rectify this with minimal code change? How to let imported
modules know
> about the namespace they are getting imported into? I do not want to
> restructure my code right now.
>
> Thanks in advance for help.


Change it so that my_imported_mod imports my_main_mod.  If A depends on
B, then A should import B, not the other way around.

If there's some good reason why B imports A despite this (and there
could be--say if myfun is some kind of a callback), then you should
probably pass myfun to the function in the imported module as an
argument.  If that's not practical, put myfun into a third module, and
have my_imported_mod import that.

If you want to live dangerously, you could do something like this from
my_main_mod:

   import my_imported_mod
   my_imported_mod.myfun = myfun

I don't recommend it, though, because my_imported_mod is no longer
self-contained (i.e., it's a module not modular).


-- 
CARL BANKS




More information about the Python-list mailing list