Python包与内部模块同名导致的导入错误原因解析
mango.mango throw a ModuleNotFoundError? Great question! This is a super common gotcha with Python's module and package resolution rules—let's break down exactly what's happening here.
First, let's recap your initial setup to make sure we're on the same page:
mango/ # This is your package folder ├── mango.py # Module with your Mango class └── test_mango.py # Test script trying to import the class
The Root Cause: Name Shadowing
When you tried running from mango.mango import Mango in test_mango.py, Python got confused because your package name (the mango folder) and your module name (the mango.py file) are identical. Here's the play-by-play:
- Python starts by looking for a package or module named
mangoin your current working directory. - Since there's both a
mangofolder (package) and amango.pyfile (module) present, Python prioritizes the module file over the package when resolving imports from within the same directory. - Instead of interpreting
mango.mangoas "themangomodule inside themangopackage", Python thinks you're trying to import something namedmangofrom themango.pymodule—which doesn't exist, hence theModuleNotFoundError.
Why Renaming to mango_main.py Fixes It
When you renamed mango.py to mango_main.py, you eliminated the name conflict:
- Now Python can clearly distinguish between the
mangopackage (folder) and themango_main.pymodule inside it. - The import
from mango.mango_main import Mangocorrectly tells Python: "Look inside themangopackage, then grab theMangoclass from themango_main.pymodule." No more confusion, no more error.
Quick Best Practice Tip
To avoid this kind of headache in the future, never name a module inside a package the same as the package itself. If you want a "primary" module for your package, stick to conventional names like main.py or __main__.py—these are recognized by Python and won't cause naming collisions.
内容的提问来源于stack exchange,提问作者Ukkyu Kang

