python - 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?
解决方案
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
.
推荐阅读
- node.js - 使用 typescript 编译问题 node.js,类型不匹配。heartBeatIntervalId 是数字类型,但 clearInterval 需要节点超时类型
- react-native - 反应原生区间,无法正确处理
- php - 代码点火器 URL 更改
- javascript - 让相机在 Aframe 中的路径上设置动画以保持专注于主题
- extjs - 在 extjs 的网格上添加启用和禁用作为上下文菜单
- docker - Docker 守护进程已经运行但仍然得到:无法连接到 unix:///var/run/docker.sock 上的 Docker 守护进程。docker 守护进程是否正在运行?
- java - 如何在 jython 中使用 cPickle 阅读
- sql - 带通配符的 BIGQUERY CASE 语句
- javascript - Vuejs如何选择按钮的范围
- python - 如何根据选择设置模型字段数据类型?