<div dir="ltr"><br><br><div class="gmail_quote"><div dir="ltr">On Mon, 2 Oct 2017 at 08:00 Christian Heimes <<a href="mailto:christian@python.org">christian@python.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">On 2017-10-02 15:26, Victor Stinner wrote:<br>
> 2017-10-02 13:10 GMT+02:00 INADA Naoki <<a href="mailto:songofacandy@gmail.com" target="_blank">songofacandy@gmail.com</a>>:<br>
>> <a href="https://github.com/python/cpython/pull/3796" rel="noreferrer" target="_blank">https://github.com/python/cpython/pull/3796</a><br>
>> In this PR, lazy loading only happens when uuid1 is used.<br>
>> But uuid1 is very uncommon for nowdays.<br>
><br>
> Antoine Pitrou added a new C extension _uuid which is imported as soon<br>
> as uuid(.py) is imported. On Linux at least, the main "overhead" is<br>
> still done on "import uuid". But Antoine change optimized a lot<br>
> "import uuid" import time!<br>
><br>
>> <a href="https://github.com/python/cpython/pull/3757" rel="noreferrer" target="_blank">https://github.com/python/cpython/pull/3757</a><br>
>> In this PR, singledispatch is lazy loading types and weakref.<br>
>> But singledispatch is used as decorator.<br>
>> So if web application uses singledispatch, it's loaded before preforking.<br>
><br>
> While "import module" is fast, maybe we should use sometimes a global<br>
> variable to cache the import.<br>
><br>
> module = None<br>
> def func():<br>
>    global module<br>
>    if module is None: import module<br>
>    ...<br>
><br>
> I'm not sure that it's possible to write an helper for such pattern.<br>
<br>
I would rather like to see a function in importlib that handles deferred<br>
imports:<br>
<br>
modulename = importlib.deferred_import('modulename')<br>
<br>
def deferred_import(name):<br>
    if name in sys.modules:<br>
        # special case 'None' here<br>
        return sys.modules[name]<br>
    else:<br>
        return ModuleProxy(name)<br>
<br>
ModuleProxy is a module type subclass that loads the module on demand.<br></blockquote><div><br></div><div>My current design for an opt-in lazy importing setup includes an explicit function for importlib that's mainly targeted for the stdlib and it's startup module needs, but could be used by others: <a href="https://notebooks.azure.com/Brett/libraries/di2Btqj7zSI/html/Lazy%20importing.ipynb">https://notebooks.azure.com/Brett/libraries/di2Btqj7zSI/html/Lazy%20importing.ipynb</a> . <br></div></div></div>