Ian Knight Ian Knight - 3 months ago 9
Python Question

Python finding some, not all custom packages

I have a project with the following file structure:

root/
run.py
bot/
__init__.py
my_discord_bot.py
dice/
__init__.py
dice.py
# dice files
help/
__init__.py
help.py
# help files
parser/
__init__.py
parser.py
# other parser files


The program is run from within the
root
directory by calling
python run.py
.
run.py
imports
bot.my_discord_bot
and then makes use of a class defined there.

The file
bot/my_discord_bot.py
has the following import statements:

import dice.dice as d
import help.help as h
import parser.parser as p


On Linux, all three import statements execute correctly. On Windows, the first two seem to execute fine, but then on the third I'm told:

ImportError: No module named 'parser.parser'; 'parser' is not a package


Why does it break on the third
import
statement, and why does it only break on Windows?

Edit: clarifies how the program is run

Answer

Make sure that your parser is not shadowing a built-in or third-party package/module/library.

I am not 100% sure about the specifics of how this name conflict would be resolved, but it seems like you can potentially a). have your module overridden by the existing module (which seems like it might be happening in your Windows case), or b). override the existing module, which could cause bugs down the road. It seems like b is what commonly trips people up.

If you think this might be happening with one of your modules (which seems fairly likely with a name like parser), try renaming your module.

See this very nice article for more details and more common Python "import traps".

Comments