[英]importlib.import_module ignoring re-exports made in __init__.py
(Originally asked on r/learnpython , but figured I'd ask here too.) (最初是在r/learnpython上问的,但我想我也会在这里问。)
Since this problem came up while dealing with django, I'll explain in that context.由于在处理 django 时出现此问题,因此我将在该上下文中进行解释。
So I have a django project folder, and some internal django apps living in that project folder, like this:因此,我有一个 django 项目文件夹,以及一些位于该项目文件夹中的内部 django 应用程序,如下所示:
project_module
├ apps
│ ├ app_module1
│ │ ├ models.py
│ │ └ ...
│ ├ app_module2
│ └ ...
├ settings.py
└ ...
now the app_modules are available as project_module.apps.app_module1
and so on, but since there won't be anything colliding with the app names in project_module
, I'd like to drop the .apps
part so I can just refer to them as project_module.app_module1
and such, consistently.现在 app_modules 可以用作
project_module.apps.app_module1
等等,但是由于不会有任何与project_module
中的应用程序名称冲突的东西,我想删除.apps
部分,所以我可以将它们称为project_module.app_module1
等,始终如一。
So, I create __init__.py
everywhere, and put this into project_module/__init__.py
:所以,我到处创建
__init__.py
,并将其放入project_module/__init__.py
:
from .apps import app_module1
And this sort of works, since I can import project_module.app_module1
and it seems to work.这种工作,因为我可以
import project_module.app_module1
并且它似乎工作。
BUT, Django internally uses importlib.import_module
here and there, and in those cases I encounter ModuleNotFoundError: No module named 'project_module.app_module1'
.但是, Django 在内部到处使用
importlib.import_module
,在这些情况下,我遇到ModuleNotFoundError: No module named 'project_module.app_module1'
。 In those cases I can use the .apps
again, but this sort of breaks consistency.在这些情况下,我可以再次使用
.apps
,但这会破坏一致性。
A bit of experiment later, I'm convinced import_module
ignores re-exports from __init__.py
;稍后进行一些实验,我确信
import_module
忽略来自__init__.py
的重新导出; But why does this happen, and is there a way I can play around this in this case?但是为什么会发生这种情况,在这种情况下我有办法解决这个问题吗?
So, I create init .py everywhere, and put this into project_module/ init .py
所以,我在任何地方都创建了init .py,并将其放入 project_module/ init .py
Consider adding project_module/apps to PYTHONPATH or sys.path
if you're really determined to remove app
from imports.如果您真的决定从导入中删除
app
,请考虑将 project_module/apps 添加到 PYTHONPATH 或sys.path
中。 That's also a hack in this use-case, but more predictable.这也是这个用例中的一个技巧,但更可预测。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.