importlib.import_module ignoring re-exports made in __init__.py

て烟熏妆下的殇ゞ 提交于 2021-01-29 16:12:52

问题


(Originally asked on r/learnpython, but figured I'd ask here too.)

Since this problem came up while dealing with django, I'll explain in that context.

So I have a django project folder, and some internal django apps living in that project folder, like this:

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.

So, I create __init__.py everywhere, and put this into 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.

BUT, Django internally uses importlib.import_module here and there, and in those cases I encounter ModuleNotFoundError: No module named 'project_module.app_module1'. In those cases I can use the .apps again, but this sort of breaks consistency.

A bit of experiment later, I'm convinced import_module ignores re-exports from __init__.py; But why does this happen, and is there a way I can play around this in this case?


回答1:


So, I create init.py everywhere, and put this into project_module/init.py

Consider adding project_module/apps to PYTHONPATH or sys.path if you're really determined to remove app from imports. That's also a hack in this use-case, but more predictable.



来源:https://stackoverflow.com/questions/61557895/importlib-import-module-ignoring-re-exports-made-in-init-py

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!