Cross Module Command Useage

Terry Hancock hancock at anansispaceworks.com
Tue Mar 14 02:22:57 CET 2006


On Sun, 12 Mar 2006 21:50:32 +0800
"Keith" <python at cgcreator.com> wrote:
> So lets say have two modules.. moduleA and moduleB. they
> are both imported into a main python program using the
> "from module import *" command. now moduleA has a dynamic
> command that needs to access a command that is in moduleB.
> but when I run these modules from the main python scrip
> they cant see each other.. it gives me an error that the
> command does not exist. Dose this mean that I need to
> import moduleB into moduleA for it to see it. or is there
> a way that I can tell moduleA too look out to the main
> python program for the commands. 

Yes, you need for "moduleA" to import "moduleB" before
it can do that.

That's not as bad as it sounds, because once you've imported
a module once, all the work is done -- later imports do
nothing except grab an existing namespace for you.

The one caveat that you get into, is don't try to design
two "friend" modules that import each other.  This results
in an impossible situation (it's recursive).

If you have something that two modules both need, and
a module which needs both of those modules, you should
break the functionality up into four modules, e.g.:

   common_utils.py
       /    \
   modA      modB
       \    /
      main_mod

I find this is a pretty common pattern for me --
there are some utilities that I write to use throughout
my code, so I put them in one module (or sub-package),
usually named "utility" or "constants" which are
imported by all modules, and then there's usually a
top or "main" module which drives everything else.

Cheers,
Terry

-- 
Terry Hancock (hancock at AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com




More information about the Python-list mailing list