importlib.import_module忽略__init__.py中进行的重新导出 [英] importlib.import_module ignoring re-exports made in __init__.py

查看:59
本文介绍了importlib.import_module忽略__init__.py中进行的重新导出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(最初在 r/learnpython ,但我也想在这里问.)

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

由于在处理django时出现了此问题,因此我将在这种情况下进行解释.

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

因此,我有一个django项目文件夹,并且该项目文件夹中包含一些内部django应用程序,如下所示:

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
└ ...

现在app_modules可以作为 project_module.apps.app_module1 等使用,但是由于 project_module 中的应用程序名称没有冲突,所以我d想删除 .apps 部分,因此我可以始终将它们称为 project_module.app_module1 之类.

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.

因此,我到处都创建 __ init __.py ,并将其放入 project_module/__ init __.py :

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

from .apps import app_module1

这样的作品,因为我可以导入project_module.app_module1 ,它似乎可以工作.

And this sort of works, since I can import project_module.app_module1 and it seems to work.

但是,Django内部到处都使用 importlib.import_module ,在这些情况下,我会遇到 ModuleNotFoundError:没有名为'project_module.app_module1'的模块.在那种情况下,我可以再次使用 .apps ,但是这种中断一致性.

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.

稍后进行一些实验,我相信 import_module 会忽略 __ init __.py 的重新导出;但是为什么会发生这种情况,在这种情况下,有什么办法可以解决这个问题?

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?

推荐答案

因此,我在各处创建 init .py,并将其放入project_module/ init .py

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

如果您确实确定要从导入中删除 app ,请考虑将project_module/apps添加到PYTHONPATH或 sys.path 中.在这个用例中,这也是一个hack,但是更容易预测.

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.

这篇关于importlib.import_module忽略__init__.py中进行的重新导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆