r/Python • u/__peg_parser__ Pythonista • 20d ago
Discussion Mysterious Lazy Imports
Run this on Python 3.15:
>>> lazy import json
>>> type(globals()['json'])
<class 'lazy_import'>Now try separating that into an innocent variable:
>>> lazy import json
>>> x = globals()['json']
>>> type(x)
<class 'module'>Looks like the same code, but what?! The output changes! Can you guess why?
(Originally asked as a Stack Overflow question, now posting here as a fun fact 😄)
63
Upvotes
83
u/toxic_acro 20d ago
From the text of PEP 810 (which added lazy imports)
Reification (i.e. replacing the lazy import proxy with the actual object) is triggered whenever the object is looked up by name, as you've done here by assigning and then using the variable
x33
u/PwAlreadyTaken 20d ago
I feel like that’s intuitive; one is peeking inside the module box, the other is taking something out and putting it in a variable.
7
u/Ducksual 20d ago
Note that:
The import is only resolved and replaced when it's loaded from globals. When you get globals as a dict it doesn't resolve the import.
x = globals()['json']assigns the lazy import object tox.Calling
type(x)looks upxin globals,xis a lazy import object so it gets resolved.2
u/VenkatKnows 10d ago
Name lookup reifies lazy objects, a dict subscript doesn't. So x holds the lazy proxy, but the moment you load x by name it resolves to the real module. Fun until it bites you in prod.
1
u/DigThatData 20d ago
didn't even realize this was a thing, guess I missed the 3.15 release
0
u/unicornshedsocial 20d ago
The difference is the load: type(x) looks x up by name (LOAD_NAME at the REPL), which reifies the proxy, while globals()[...] hands you the raw dict value. Did the Stack Overflow answer explain it that way?
-2
u/ShelLuser42 It works on my machine 20d ago edited 20d ago
My guess is the lazy import even though I never used it before.
My assumption, based on the output, is that it adds an "interface" which fact checks if the imported object gets addressed, and if so that routine takes care of doing the actual import check(s) afterwards.
(edit)
So what I'm saying: assigning it to a variable triggers that "interface", thus leaving you with the end result.
-6
u/Rudeus_Kino 20d ago
In python you can override assignment, just write get_.
-8
u/ohnoitssobig 20d ago
Trivially answered by looking at the bytecode.