Module Packages

Gordon McMillan gmcm at hypernet.com
Sat Feb 26 08:06:05 EST 2000


alxchltn at my-deja.com wrote:

> I'm trying to write a package consisting of four modules that are all in
> the same folder. After a series of choices from the first module, the
> second module is called and so on. When module 2 tries to call a
> function from the first, It raises an error - "no function named..."
> Should I be using something else besides "from <filename> import *",
> adding something to "__init__.py" or just make a copy of the function
> and paste it to module 2.
> I don't just want it to work, I want it to work proper.

With your vague description, we can only guess what's going 
on.

First, don't use "from mod import *". It's not a piece of 
syntactic sugar that lets you magically not type the module 
name. It looks inside "mod" and makes bindings in this 
module for all the names it finds in "mod", then it throws away 
"mod".

Now consider when your main imports mod1, and mod1 
imports mod2, and mod2 imports mod1.

In main, the "import mod1" line is hit.
Python starts loading mod1.
In mod1, the "import mod2" line is hit.
Python starts loading mod2.
The line "import mod1" is hit.
Python detects the recursion, and just goes ahead, under the 
assumption that by the time all this loading has completed, 
mod1 will indeed be there.
So mod2 completes loading (but with a reference to mod1 that 
is not yet good enough to use).
Then mod1 completes loading (and the reference in mod2 is 
now usable).

So if mod2 did "from mod1 import *" it got nothing, because at 
the point that line executed, mod1 was nothing but an empty 
shell.

- Gordon




More information about the Python-list mailing list