[New-bugs-announce] [issue32192] Provide importlib.util.lazy_import helper function

Nick Coghlan report at bugs.python.org
Fri Dec 1 03:50:41 EST 2017

New submission from Nick Coghlan <ncoghlan at gmail.com>:

While importlib provides all the *pieces* to implement lazy imports, we don't actually provide a clear way of chaining them together into a lazy import operation. Without any error checking, that looks like:

    import sys
    import importlib.util
    def lazy_import(name):
        spec = importlib.util.find_spec(name)
        loader = importlib.util.LazyLoader(spec.loader)
        spec.loader = loader
        module = importlib.util.module_from_spec(spec)
        sys.modules[name] = module
        return module

    >>> lazy_typing = lazy_import("typing")
    >>> lazy_typing.TYPE_CHECKING

I'm thinking it may make sense to just provide a robust implementation of that, and accept that it may lead to some bug reports that are closed with "You need to fix the module you're loading to be compatible with lazy imports"

messages: 307370
nosy: ncoghlan
priority: normal
severity: normal
status: open
title: Provide importlib.util.lazy_import helper function

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list