Manually creating a "package" by setting __path__
would be a really weird thing to do, and I've never seen a use case for it. The import system core should handle it correctly, but code that expects "normal" packages is likely to break in all sorts of exotic ways. You probably shouldn't do this.
That said, what you're asking for would be as simple as putting
__path__ = ['whatever', 'list', 'of', 'directories', 'you', 'want']
in the module you want Python to treat as a package. Python will then treat the module as a package, and look for submodules in the directories specified in your artificial __path__
.
For example, if you have the following directory structure:
.
├── contents
│ └── submodule.py
└── package.py
where package.py
contains
import os
__path__ = [os.path.join(os.path.dirname(os.path.abspath(__file__)), 'contents')]
and contents/submodule.py
contains
x = 3
then import package.submodule
will treat package.py
as a package and contents/submodule.py
as the package.submodule
submodule of the package
package, and package.submodule.x
will resolve to 3
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…