Lazy Loading Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Lazy Loading runs in O(1) time and O(1) space, in Python as in every other language.
- ✓functools.cached_property is the per-instance answer: it writes the computed value straight into instance.__dict__ under the property's own name.
- ✓Reviewers reach for the decorator before the hand-rolled self._x = None sentinel, because a None sentinel cannot distinguish not-yet-built from built-and-legitimately-None.
- ✓The Python trap: cached_property is a non-data descriptor: it defines __get__ and __set_name__ but no __set__, so once the value lands in the instance dictionary that entry shadows the descriptor and the body never runs again.
- ✓After the first read there is no descriptor protocol left in the path: attribute lookup finds the instance-dictionary entry and returns it, so steady-state cost equals any ordinary attribute.
What Lazy Loading actually is
Lazy Loading in Python: what you actually reach for
Python implementation
import threading
from functools import cached_property
_TABLE_LOCK = threading.Lock()
_table: dict[str, int] | None = None
def opcode_table() -> dict[str, int]:
# Explicit double-checked locking. The GIL does not make this free: the
# test and the store are separate bytecodes with a switch point between.
global _table
table = _table
if table is None:
with _TABLE_LOCK:
if _table is None:
_table = {"nop": 0x00, "push": 0x10, "add": 0x20, "jmp": 0x30}
table = _table
return table
class Disassembler:
# No __slots__ on purpose: cached_property stores into instance.__dict__,
# and a slotted class raises TypeError on the first read.
def __init__(self, blob: bytes) -> None:
self.blob = blob
@cached_property
def reverse(self) -> dict[int, str]:
# Since 3.12 cached_property holds no lock, so two threads racing a
# cold instance both run this body. Fine for a pure value, not fine
# if it opened a socket or registered a handler.
return {v: k for k, v in opcode_table().items()}
def mnemonics(self) -> list[str]:
return [self.reverse.get(b, "??") for b in self.blob]
def __getattr__(name: str):
# PEP 562 module __getattr__: imported on first attribute access, then
# written into globals(), which shadows this hook from then on.
if name == "pretty":
from pprint import pformat
globals()["pretty"] = pformat
return pformat
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Lazy Loading?
functools.cached_property is the per-instance answer: it writes the computed value straight into instance.__dict__ under the property's own name. For a zero-argument factory at module scope, functools.cache memoises the function itself. Shared mutable state needs threading.Lock supplied by you, because nothing in functools synchronises anything. Deferred code has two forms: PEP 562 module-level __getattr__, which lets a package resolve an attribute by importing on demand, and importlib.util.LazyLoader wrapped around the loader from importlib.util.find_spec, which yields a module object whose body does not execute until an attribute is touched.
What is the most common Python mistake when implementing Lazy Loading?
cached_property is a non-data descriptor: it defines __get__ and __set_name__ but no __set__, so once the value lands in the instance dictionary that entry shadows the descriptor and the body never runs again. Two consequences bite only here. A class with __slots__ has no __dict__, so the very first read raises TypeError: No '__dict__' attribute on ... to cache. And Python 3.12 removed the internal lock the decorator used to hold, so two threads racing a cold instance both execute the body and the second store wins. A pure value survives that. A factory that opens a file handle leaks one per loser.
How does Lazy Loading actually perform in Python?
After the first read there is no descriptor protocol left in the path: attribute lookup finds the instance-dictionary entry and returns it, so steady-state cost equals any ordinary attribute. A plain @property is a data descriptor, permanently outranks the instance dictionary, and therefore pays a full interpreter-level call on every access forever. functools.cache on a nullary function is slower than it looks, since each call still hashes the empty argument tuple and probes the cache dict. A deferred import moves the sys.modules write and the module body execution to first access, it does not remove them. Time complexity is O(1) and space is O(1).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialBefore paying full price for a tool, check the student deals on AI and developer tools listed on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.