[Tutor] module import from a packager works inconsistent between REPL and command line

Steven D'Aprano steve at pearwood.info
Fri Apr 26 01:28:05 EDT 2019


On Thu, Apr 25, 2019 at 05:40:18PM +0530, Arup Rakshit wrote:

> I have a small app like this:

Please simplify your code to the minimum needed to demonstrate the 
problem you are asking about. This bit is excellent:

> pizza-shop$ tree .
> .
> └── pizzapy
>     ├── __init__.py
>     ├── menu.py
>     └── pizza.py
> 
> 1 directory, 3 files

Nicely shown!

But we don't need to see all the gory details of menu.py and especially 
not of pizza.py, all those methods in pizza.Pizza are irrelevant to the 
problem. Please read this:

http://www.sscce.org/

for a guide. It is written for Java programmers, but it applies to any 
language.

All we need in menu.py is a single line:

# menu.py 
from pizza import Pizza

because that's the line that fails.

And for pizza.py, all we need is:

# pizza.py 
Pizza = None


> Now when I call the menu.py from command like it works as expected.

When you ask Python to import a module, it doesn't search the entire 
hard drive, that could take hours if the drive is big enough. It only 
looks in the search-path. At runtime, you can see the paths searched 
like this:

import sys
print(sys.path)

which will show you where Python is looking for modules.

When you directly call a module:

    python path/to/menu.py

the directory holding that module is included in the search path, so if 
you also have path/to/pizza.py the "import pizza" will work.

But in the REPL, only the default search path is used. 

In your case, the fix is, I think, to change menu.py to do this:

# was: from pizza import Pizza
from pizzapy.pizza import Pizza

which I *think* will solve the problem, but I haven't tested it.

For what it is worth, importing problems are sometimes annoying to 
solve. What works as a good design for importing libraries doesn't 
always make a good design for scripts that you call directly from the 
command line, and visa versa, so the import system is a bit of a 
compromise between the two.



-- 
Steven


More information about the Tutor mailing list