|
|
Subscribe / Log in / New account

The return of lazy imports for Python

The return of lazy imports for Python

Posted Dec 14, 2022 3:28 UTC (Wed) by nybble41 (subscriber, #55106)
In reply to: The return of lazy imports for Python by mb
Parent article: The return of lazy imports for Python

The repeated import issue doesn't seem that difficult to work around:

def lazy_foo():
    if not hasattr(lazy_foo, "cached"):
        import foo
        lazy_foo.cached = foo
    return lazy_foo.cached

def func1():
    lazy_foo().bar()

def func2():
    lazy_foo().baz()

This will import foo exactly once, the first time either func1() or func2() calls lazy_foo(). After that lazy_foo() just returns the module which was already imported.


to post comments

The return of lazy imports for Python

Posted Dec 14, 2022 6:03 UTC (Wed) by NYKevin (subscriber, #129325) [Link] (1 responses)

That has to call an entire function, compared to looking up a global. Even if the LOAD_GLOBAL code path grows a little extra complexity for lazy objects, a function call is still much more expensive, because it sets up and tears down an entire stack frame object. If you do that pervasively throughout the entire application, you'll end up churning the heap allocator unnecessarily (Python puts frame objects on the heap so that they can be referenced and kept alive by traceback objects when an exception is thrown).

The return of lazy imports for Python

Posted Dec 16, 2022 5:24 UTC (Fri) by mgedmin (subscriber, #34497) [Link]

Python 3.11 creates frame objects lazily, only when needed. I wonder how that affects this consideration.

The return of lazy imports for Python

Posted Dec 25, 2022 21:35 UTC (Sun) by empiko (guest, #162849) [Link]

Alternatively, you can do this:
foo = None

def func():
    if foo is None:
        import foo
    ...


Copyright © 2025, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds