On 26/04/19 10:58 AM, Steven D'Aprano wrote:
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.
Thanks for explaining this. I got it, it is terrible confusing for a
beginner untill spent some months and use Python daily. Every beginner
will be frustated, and probably think to give up the whole Python
journey.. haha. Some StackOverflow posts shown modifying sys.path by
inserting at position 0, it felt to me as a hacked workaround.. So came
here to know how to cook 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.
Yes, yes.
--
Thanks,
Arup Rakshit
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor