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.
Posted Dec 14, 2022 6:03 UTC (Wed)
by NYKevin (subscriber, #129325)
[Link] (1 responses)
Posted Dec 16, 2022 5:24 UTC (Fri)
by mgedmin (subscriber, #34497)
[Link]
Posted Dec 25, 2022 21:35 UTC (Sun)
by empiko (guest, #162849)
[Link]
The return of lazy imports for Python
The return of lazy imports for Python
Alternatively, you can do this:
The return of lazy imports for Python
foo = None
def func():
if foo is None:
import foo
...
