首页 > 解决方案 > How to make a module act as package with __path__ variable?

问题描述

I was trying to dig deep into python import mechanism and came across this in the Packages section of the documentation:

It’s important to keep in mind that all packages are modules, but not all modules are packages. Or put another way, packages are just a special kind of module. Specifically, any module that contains a __path__ attribute is considered a package.

It looks interesting but I could not find any example demonstrating this! So, how to actually implement it? In real world scenarios do you ever need such implementation?

标签: pythonpython-3.xpython-import

解决方案


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.


推荐阅读