延迟加载模块在__init__.py文件python中导入 [英] Lazy loading module imports in an __init__.py file python

查看:185
本文介绍了延迟加载模块在__init__.py文件python中导入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人对 init 文件中的延迟加载导入有任何建议?我目前有以下文件夹结构:

I was wondering if anyone had any suggestions for lazy loading imports in an init file? I currently have the following folder structure:

/mypackage
    __init__.py
    /core
        __init__.py
        mymodule.py
        mymodule2.py

.py文件包含以下导入:

The init.py file in the core folder with the following imports:

from mymodule import MyModule
from mymodule2 import MyModule2

这样我可以做:

from mypackage.core import MyModule, MyModule2

但是,在包 init .py文件中,我还有另一个导入:

However, in the package init.py file, I have another import:

from core.exc import MyModuleException

这就是每当我在python中导入我的包时,MyModule和MyModule2都会导入默认情况下,因为核心 init .py文件已经运行。

This has the effect that whenever I import my package in python, MyModule and MyModule2 get imported by default because the core init.py file has already been run.

我想要做的只是导入这些模块w下面的代码运行而不是之前:

What I want to do, is only import these modules when the following code is run and not before:

from mypackage.core import MyModule, MyModule2

任何想法?

非常感谢。

推荐答案

你做不到。请记住,当python导入时,它会执行模块中的代码。模块本身不知道它是如何导入的,因此无法知道是否必须导入 MyModule(2)

You can't. Remember that when python imports it executes the code in the module. The module itself doesn't know how it is imported hence it cannot know whether it has to import MyModule(2) or not.

你必须从mypackage.core中选择:允许从core.exc导入A,B 导入E 不需要的导入(x)是否导入 A B core / __ init __。py 中,因此不允许来自mypackage.core导入的导入A,B

You have to choose: allow from mypackage.core import A, B and from core.exc import E does the non-needed imports (x)or do not import A and B in core/__init__.py, hence not allowing from mypackage.core import A, B.

注意:我个人不会在核心中导入 MyModule(2) / __ init __。py ,但我会添加一个 all.py 模块,这样做,所以用户可以做来自mypackage.core.all导入A,B
并且仍然从mypackage.core.exc导入导入TheException 不加载不必要的类。

Note: Personally I would not import MyModule(2) in core/__init__.py, but I'd add an all.py module that does this, so the user can do from mypackage.core.all import A, B and still have from mypackage.core.exc import TheException not loading the unnecessary classes.

(实际上:所有模块甚至可以修改 mypackage.core 并将类添加到其中,以便跟随导入类型来自mypackage.core导入MyModule,MyModule2 工作,但我觉得这很晦涩,应该避免使用。)

(Actually: the all module could even modify mypackage.core and add the classes to it, so that following imports of the kind from mypackage.core import MyModule, MyModule2 work, but I think this would be quite obscure and should be avoided).

这篇关于延迟加载模块在__init__.py文件python中导入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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