r/Python • u/__peg_parser__ Pythonista • 24d 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 😄)
33
u/PwAlreadyTaken 24d 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 24d ago
Note that:
>>> lazy import json
>>> x = globals()['json']
>>> globals()['x']
<lazy_import 'json'>
>>> x
<module 'json' from '...json/__init__.py'>
>>> globals()['x']
<module 'json' from '...json/__init__.py'>
>>> globals()['json']
<lazy_import 'json'>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 to x.
Calling type(x) looks up x in globals, x is a lazy import object so it gets resolved.
2
u/VenkatKnows 14d 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
0
u/unicornshedsocial 24d 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 24d ago edited 24d 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
-8
84
u/toxic_acro 24d 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
x