为何Python包内模块两种导入方式一可行一报错?已尝试__init__.py与PYTHONPATH
sum_module via sum_package.sum_module even after setting PYTHONPATH? First, let's recap your project structure for clarity:
project/ ├── sum_package/ │ └── sum_module.py └── testing.py
You've noticed that from sum_package import sum_module works perfectly, but import sum_package followed by sum_package.sum_module.great_summation(1,2) throws an AttributeError: module 'sum_package' has no attribute 'sum_module'—even after adding __init__.py and setting PYTHONPATH. Here's why:
The core issue: Python doesn't auto-import submodules in packages
When you import sum_package, Python only loads the package itself (which means executing the __init__.py file in the sum_package directory, if it exists). It does not automatically scan and import all submodules inside the package unless you explicitly tell it to.
In contrast, from sum_package import sum_module directly tells Python to locate and load the sum_module submodule, which is why that method works without extra steps.
Why your empty __init__.py didn't help
If you added an empty __init__.py file, it just marks sum_package as a valid Python package, but it doesn't trigger the import of sum_module. To make sum_package.sum_module accessible, you need to explicitly import the submodule inside sum_package/__init__.py.
The fix: Update your package's __init__.py
Edit sum_package/__init__.py to include either of these lines:
# Option 1: Relative import from . import sum_module # Option 2: Absolute import import sum_package.sum_module
Once you do this, when you run import sum_package, Python will execute the __init__.py file, which imports sum_module and attaches it to the sum_package namespace. Now sum_package.sum_module.great_summation(1,2) will work as expected.
A note on PYTHONPATH
Your export PYTHONPATH="$PWD" command is correct—it ensures Python can find the sum_package package when running testing.py from the project directory. However, PYTHONPATH only controls where Python looks for packages/modules to import; it doesn't change how packages handle their submodules. That's why setting it didn't fix the attribute error.
内容的提问来源于stack exchange,提问作者ilmoi

