Skip to content

Commit f151e7b

Browse files
committed
Add a minimal reproduction for lazy loading issues
0 parents commit f151e7b

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

foo.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import sys
2+
import types
3+
4+
class Foo(types.ModuleType):
5+
@property
6+
def bar(self) -> str:
7+
return "Hello from foo.bar"
8+
9+
sys.modules[__name__].__class__ = Foo

main.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import importlib.util
2+
import sys
3+
4+
def lazy(fullname):
5+
m = sys.modules.get(fullname, None)
6+
if m is not None:
7+
return m
8+
9+
spec = importlib.util.find_spec(fullname)
10+
11+
# Return early if find_spec has recursively called lazy_import
12+
# again and pre-populated the sys.modules slot; an example of this
13+
# is covered by test_lazy_import.
14+
m = sys.modules.get(fullname, None)
15+
if m is not None:
16+
return m
17+
18+
loader = importlib.util.LazyLoader(spec.loader)
19+
spec.loader = loader
20+
module = importlib.util.module_from_spec(spec)
21+
22+
# Return early rather than overwriting the sys.modules slot.
23+
m = sys.modules.get(fullname, None)
24+
if m is not None:
25+
return m
26+
27+
sys.modules[fullname] = module
28+
loader.exec_module(module)
29+
return module
30+
31+
foo = lazy("foo")
32+
33+
print(foo.bar)

0 commit comments

Comments
 (0)