Skip to content

Commit b738405

Browse files
committed
Changes code core!!!
1 parent ecca600 commit b738405

1 file changed

Lines changed: 149 additions & 8 deletions

File tree

‎lazyimports/core.py‎

Lines changed: 149 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
__all__ = [
2323
"NATIVE_LAZY_IMPORT",
2424
"SUPPORT_LAZY_IMPORT",
25+
"SETATTR_TARGET",
2526
"LazyModule",
2627
"lazy_import",
2728
"lazy_from",
@@ -31,7 +32,7 @@
3132
]
3233

3334

34-
#License MIT <aiwonderland> in <2026>
35+
# License MIT <aiwonderland> in <2026>
3536

3637
# Native `lazy import` statement is available on Python 3.15+.
3738
NATIVE_LAZY_IMPORT = sys.version_info >= (3, 15)
@@ -42,6 +43,35 @@
4243
# always supported regardless of interpreter version.
4344
SUPPORT_LAZY_IMPORT = True
4445

46+
# License MIT <aiwonderland> in <2026>
47+
48+
# ---------------------------------------------------------------------------
49+
# Module-level configuration
50+
# ---------------------------------------------------------------------------
51+
52+
# Controls where ``LazyModule.__setattr__`` writes non-internal
53+
# attributes when the real module has not yet been loaded (or when
54+
# loading has failed).
55+
#
56+
# Accepted values:
57+
# * ``"module"`` (default, backward-compatible): the attribute is
58+
# forwarded to the underlying module via ``setattr(real, ...)``.
59+
# This means a value written through the proxy becomes visible
60+
# globally (because Python modules are singletons in
61+
# ``sys.modules``). This matches the behaviour of ordinary
62+
# ``import foo`` followed by ``foo.bar = ...``.
63+
# * ``"proxy"``: the attribute is mounted on the proxy shell via
64+
# ``object.__setattr__(self, ...)``. The underlying module is
65+
# **not** loaded as a side effect, and the value is visible only
66+
# through this proxy instance. Use this when you want to attach
67+
# scratch state to a lazy module without paying for the import
68+
# or polluting the real module's namespace.
69+
#
70+
# Why a global instead of a per-instance flag? The two modes are
71+
# not usually mixed in the same project; a single global keeps the
72+
# API surface small. Change at your own risk and reset it before any
73+
# code that expects the default behaviour runs.
74+
SETATTR_TARGET = "module"
4575

4676
# GNUv3 License, add in <2018>, by <Evan Yang>
4777
class LazyModule(types.ModuleType):
@@ -51,63 +81,174 @@ class LazyModule(types.ModuleType):
5181
instantiated directly. The proxy behaves like the underlying
5282
module, but the real module is not imported until an attribute is
5383
actually requested. Once loaded, the real module is cached.
84+
85+
Failure handling
86+
----------------
87+
If the first import attempt raises ``ImportError`` (typically
88+
because the module does not exist), the exception is **cached**
89+
on the proxy and re-raised on every subsequent attribute access
90+
— the import system is not asked again. This prevents a missing
91+
optional dependency from being retried on every attribute access
92+
in a hot loop. Use :func:`force_load` if you need to retry after
93+
installing the dependency.
94+
95+
Magic methods
96+
-------------
97+
Python looks up operator dunders (``__eq__``, ``__lt__``,
98+
``__hash__``, ``__bool__``, ``__repr__``, etc.) on the **type**,
99+
not the instance, so they never go through ``__getattr__`` and
100+
therefore never trigger the lazy import. The handful we define
101+
(``__hash__``, ``__bool__``, ``__eq__``, ``__ne__``, ``__repr__``)
102+
are based purely on the target module name, which is known at
103+
proxy-construction time. As a consequence:
104+
105+
* Two proxies for the same module compare equal
106+
(``a == b`` when ``a._target() == b._target()``).
107+
* Hashing is consistent with equality.
108+
* A proxy is always truthy (``bool(proxy) is True``).
109+
110+
Other operators (``<``, ``<=``, ``+``, …) fall back to
111+
``object``'s default identity-based behaviour; if you need
112+
ordering, compare the target names explicitly.
113+
114+
``__dir__``
115+
-----------
116+
Before the proxy is loaded, ``dir(proxy)`` returns the slot names
117+
plus ``types.ModuleType``'s attributes. If the target module is
118+
already present in ``sys.modules`` (because something else
119+
imported it first), the contents of that module's ``__all__``
120+
are merged in so REPL / IDE completion sees the real exports.
54121
"""
55122

56-
__slots__ = ("_lazy_target", "_lazy_real")
123+
__slots__ = ("_lazy_target", "_lazy_real", "_lazy_error")
57124

58125
def __init__(self, name):
59126
super().__init__(name)
127+
# Use ``object.__setattr__`` because we override ``__setattr__``
128+
# to forward writes to the real module once it has been loaded.
60129
object.__setattr__(self, "_lazy_target", name)
61130
object.__setattr__(self, "_lazy_real", None)
131+
# Cached ``ImportError`` from a failed first-resolve attempt.
132+
# ``None`` means "no failure recorded yet". The presence of a
133+
# truthy value short-circuits future ``_resolve()`` calls and
134+
# prevents repeated import attempts.
135+
object.__setattr__(self, "_lazy_error", None)
62136

63137
def _target(self):
138+
# Return the fully-qualified module name stored at construction.
139+
# Defined as a method (not a property) so it does not collide
140+
# with ``__getattr__``-driven attribute forwarding.
64141
return object.__getattribute__(self, "_lazy_target")
65142

66143
def _resolve(self):
144+
# Two-state cache: either the real module is loaded, or we
145+
# have a cached exception to re-raise. Anything else means
146+
# this is the first call and we attempt the import.
67147
real = object.__getattribute__(self, "_lazy_real")
68-
if real is None:
148+
if real is not None:
149+
return real
150+
error = object.__getattribute__(self, "_lazy_error")
151+
if error is not None:
152+
raise error
153+
try:
69154
real = import_module(self._target())
70-
object.__setattr__(self, "_lazy_real", real)
155+
except ImportError as exc:
156+
# Cache the exception so we don't retry. The original
157+
# traceback is preserved on the cached exception object.
158+
object.__setattr__(self, "_lazy_error", exc)
159+
raise
160+
object.__setattr__(self, "_lazy_real", real)
71161
return real
72162

73163
def __getattr__(self, name):
164+
# ``_lazy_*`` attributes are managed via ``object.__setattr__``;
165+
# asking for one on a not-yet-loaded module would otherwise
166+
# recurse here, so guard explicitly.
74167
if name.startswith("_lazy_"):
75168
raise AttributeError(name)
76169
return getattr(self._resolve(), name)
77170

78171
def __setattr__(self, name, value):
172+
# Internal ``_lazy_*`` slots always live on the proxy shell.
79173
if name.startswith("_lazy_"):
80174
object.__setattr__(self, name, value)
81175
return
176+
# Behaviour is controlled by the module-level ``SETATTR_TARGET``
177+
# flag. See the flag's docstring for the rationale.
178+
if SETATTR_TARGET == "proxy":
179+
object.__setattr__(self, name, value)
180+
return
181+
# Default: forward to the underlying module. This both loads
182+
# the module (if it has not been loaded yet) and makes the
183+
# attribute visible through every reference to that module.
82184
setattr(self._resolve(), name, value)
83185

84186
def __delattr__(self, name):
85187
if name.startswith("_lazy_"):
86188
object.__delattr__(self, name)
87189
return
190+
# Deleting an attribute on a proxy implies the real module
191+
# is intended to be touched — we never silently unmount
192+
# shell-only state because there is none in the default mode.
88193
delattr(self._resolve(), name)
89194

90195
def __dir__(self):
91196
if object.__getattribute__(self, "_lazy_real") is None:
92-
# return sorted(set(self.__slots__) | set(dir(types.ModuleType)))
93-
# Try to support python 3.6, forgot this :(
197+
# Module hasn't been loaded yet by us. Show a static
198+
# baseline so introspection tools do not raise.
94199
attrs = set(dir(types.ModuleType))
95200
attrs.update(self.__slots__)
201+
# If the target module was already imported by some other
202+
# code path, surface its ``__all__`` so REPL completion
203+
# and IDEs see the real exports even before we touch it.
204+
target = self._target()
205+
already_loaded = sys.modules.get(target)
206+
if already_loaded is not None:
207+
all_attr = getattr(already_loaded, "__all__", None)
208+
if all_attr:
209+
attrs.update(all_attr)
96210
return sorted(attrs)
97211
return dir(self._resolve())
98212

99213
def __repr__(self):
100214
real = object.__getattribute__(self, "_lazy_real")
101215
if real is None:
216+
error = object.__getattribute__(self, "_lazy_error")
217+
if error is not None:
218+
return "<lazy module {!r} [failed: {}]>".format(
219+
self._target(), error
220+
)
102221
return "<lazy module {!r} [not loaded]>".format(self._target())
103222
return repr(real)
104223

105224
def __bool__(self):
225+
# A lazy proxy is always truthy, even before its target loads.
226+
# Modules are typically used for their side effects / attributes,
227+
# so truthiness should not depend on the load state.
106228
return True
107229

108230
def __hash__(self):
231+
# Hash by target name so equal proxies hash equally and can
232+
# be used interchangeably as dict keys. Defined as a dunder
233+
# (rather than via ``__getattr__``) so it works before the
234+
# underlying module is loaded.
109235
return hash(self._target())
110236

237+
def __eq__(self, other):
238+
# Two proxies are equal when their targets match. Defined as
239+
# a dunder so it does not trigger a lazy import — useful in
240+
# tests and debugging where you want to compare proxy
241+
# identity without paying the import cost.
242+
if isinstance(other, LazyModule):
243+
return self._target() == other._target()
244+
return NotImplemented
245+
246+
def __ne__(self, other):
247+
result = self.__eq__(other)
248+
if result is NotImplemented:
249+
return result
250+
return not result
251+
111252

112253
# GNUv3 License, add in <2018>, by <Evan Yang>
113254
def lazy_import(name, package=None):
@@ -139,7 +280,7 @@ def lazy_import(name, package=None):
139280
"""
140281
if package is not None:
141282
# real_name = importlib.import_module(name, package).__name__
142-
283+
143284
# Old code imports module eagerly and defeats lazy loading.
144285
# Switch to resolve_name to resolve name without importing.
145286
real_name = resolve_name(name, package)
@@ -164,7 +305,7 @@ def lazy_from(module, *names):
164305
-------
165306
LazyModule or tuple
166307
If `names` is empty, returns the module proxy. Otherwise
167-
returns a tuple of `LazyAttr` wrappers; each wrapper triggers
308+
returns a tuple of `_LazyAttr` wrappers; each wrapper triggers
168309
the underlying import on first access.
169310
170311
Examples

0 commit comments

Comments
 (0)