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

Viewed 390

Python's docs say that there's an alternative to local imports to prevent loading the module on startup:

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.

1 Answers

The documentation likely refers to the use of importlib.import_module, which exposes Python's import functionality:

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 e.g. 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)
Related