简体   繁体   English

我如何做python unittest doc推荐的懒惰导入方法?

[英]How do I do python unittest doc's recommended method of lazy import?

Python's docs say that there's an alternative to local imports to prevent loading the module on startup: Python的文档说,有一种替代本地导入,以防止在启动时加载模块:

https://docs.python.org/3/library/unittest.mock-examples.html#mocking-imports-with-patch-dict https://docs.python.org/3/library/unittest.mock-examples.html#mocking-imports-with-patch-dict

...to prevent “up front costs” by delaying the import. ......通过推迟进口来防止“前期成本”。 This can also be solved in better ways than an unconditional local import (store the module as a class or module attribute and only do the import on first use). 这也可以通过比无条件本地导入更好的方式解决(将模块存储为类或模块属性,并且仅在首次使用时执行导入)。

I don't understand the explanation in brackets. 我不明白括号中的解释。 How do I do this? 我该怎么做呢? However I think about it, I seem to end up with local imports anyway. 不过我考虑一下,无论如何,我似乎最终都是本地进口商品。

The documentation likely refers to the use of importlib.import_module , which exposes Python's import functionality: 该文档可能涉及使用importlib.import_module ,它暴露了Python的import功能:

import importlib

class Example():

    TO_IMPORT = "os"  # the name of the module to lazily import
    __module = None

    def __init__(self):
        if self.__module is None:
            self.__module = importlib.import_module(self.TO_IMPORT)

Note that this way the module is only imported once when the class is first instantiated and is not available in global namespace. 请注意,这样,模块仅在首次实例化类时导入一次,并且在全局命名空间中不可用。

Further, it allows you to change which module is imported, which could be useful eg in cases where the same class is used as an interface to different backends: 此外,它允许您更改导入的模块,这可能是有用的,例如在将相同的类用作不同后端的接口的情况下:

import importlib

class Example():

    def __init__(self, backend="some_module"):
        self.module = importlib.import_module(backend)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM