| 1 |
# demandimportpy3 - global demand-loading of modules for Mercurial |
| 2 |
# |
| 3 |
# Copyright 2017 Facebook Inc. |
| 4 |
# |
| 5 |
# This software may be used and distributed according to the terms of the |
| 6 |
# GNU General Public License version 2 or any later version. |
| 7 |
|
| 8 |
"""Lazy loading for Python 3.6 and above. |
| 9 |
|
| 10 |
This uses the new importlib finder/loader functionality available in Python 3.5 |
| 11 |
and up. The code reuses most of the mechanics implemented inside importlib.util, |
| 12 |
but with a few additions: |
| 13 |
|
| 14 |
* Allow excluding certain modules from lazy imports. |
| 15 |
* Expose an interface that's substantially the same as demandimport for |
| 16 |
Python 2. |
| 17 |
|
| 18 |
This also has some limitations compared to the Python 2 implementation: |
| 19 |
|
| 20 |
* Much of the logic is per-package, not per-module, so any packages loaded |
| 21 |
before demandimport is enabled will not be lazily imported in the future. In |
| 22 |
practice, we only expect builtins to be loaded before demandimport is |
| 23 |
enabled. |
| 24 |
""" |
| 25 |
|
| 26 |
from __future__ import annotations |
| 27 |
|
| 28 |
import contextlib |
| 29 |
import importlib.util |
| 30 |
import sys |
| 31 |
|
| 32 |
from . import tracing |
| 33 |
|
| 34 |
_deactivated = False |
| 35 |
|
| 36 |
|
| 37 |
class _lazyloaderex(importlib.util.LazyLoader): |
| 38 |
"""This is a LazyLoader except it also follows the _deactivated global and |
| 39 |
the ignore list. |
| 40 |
""" |
| 41 |
|
| 42 |
_HAS_DYNAMIC_ATTRIBUTES = True # help pytype not flag self.loader |
| 43 |
|
| 44 |
def exec_module(self, module): |
| 45 |
"""Make the module load lazily.""" |
| 46 |
with tracing.log('demandimport %s', module): |
| 47 |
if _deactivated or module.__name__ in ignores: |
| 48 |
# Reset the loader on the module as super() does (issue6725) |
| 49 |
module.__spec__.loader = self.loader |
| 50 |
module.__loader__ = self.loader |
| 51 |
|
| 52 |
self.loader.exec_module(module) |
| 53 |
else: |
| 54 |
super().exec_module(module) |
| 55 |
|
| 56 |
|
| 57 |
class LazyFinder: |
| 58 |
"""A wrapper around a ``MetaPathFinder`` that makes loaders lazy. |
| 59 |
|
| 60 |
``sys.meta_path`` finders have their ``find_spec()`` called to locate a |
| 61 |
module. This returns a ``ModuleSpec`` if found or ``None``. The |
| 62 |
``ModuleSpec`` has a ``loader`` attribute, which is called to actually |
| 63 |
load a module. |
| 64 |
|
| 65 |
Our class wraps an existing finder and overloads its ``find_spec()`` to |
| 66 |
replace the ``loader`` with our lazy loader proxy. |
| 67 |
|
| 68 |
We have to use __getattribute__ to proxy the instance because some meta |
| 69 |
path finders don't support monkeypatching. |
| 70 |
""" |
| 71 |
|
| 72 |
__slots__ = ("_finder",) |
| 73 |
|
| 74 |
def __init__(self, finder): |
| 75 |
object.__setattr__(self, "_finder", finder) |
| 76 |
|
| 77 |
def __repr__(self): |
| 78 |
return "<LazyFinder for %r>" % object.__getattribute__(self, "_finder") |
| 79 |
|
| 80 |
# __bool__ is canonical Python 3. But check-code insists on __nonzero__ being |
| 81 |
# defined via `def`. |
| 82 |
def __nonzero__(self): |
| 83 |
return bool(object.__getattribute__(self, "_finder")) |
| 84 |
|
| 85 |
__bool__ = __nonzero__ |
| 86 |
|
| 87 |
def __getattribute__(self, name): |
| 88 |
if name in ("_finder", "find_spec"): |
| 89 |
return object.__getattribute__(self, name) |
| 90 |
|
| 91 |
return getattr(object.__getattribute__(self, "_finder"), name) |
| 92 |
|
| 93 |
def __delattr__(self, name): |
| 94 |
return delattr(object.__getattribute__(self, "_finder"), name) |
| 95 |
|
| 96 |
def __setattr__(self, name, value): |
| 97 |
return setattr(object.__getattribute__(self, "_finder"), name, value) |
| 98 |
|
| 99 |
def find_spec(self, fullname, path, target=None): |
| 100 |
finder = object.__getattribute__(self, "_finder") |
| 101 |
try: |
| 102 |
find_spec = finder.find_spec |
| 103 |
except AttributeError: |
| 104 |
loader = finder.find_module(fullname, path) |
| 105 |
if loader is None: |
| 106 |
spec = None |
| 107 |
else: |
| 108 |
spec = importlib.util.spec_from_loader(fullname, loader) |
| 109 |
else: |
| 110 |
spec = find_spec(fullname, path, target) |
| 111 |
|
| 112 |
# Lazy loader requires exec_module(). |
| 113 |
if ( |
| 114 |
spec is not None |
| 115 |
and spec.loader is not None |
| 116 |
and getattr(spec.loader, "exec_module", None) |
| 117 |
): |
| 118 |
spec.loader = _lazyloaderex(spec.loader) |
| 119 |
|
| 120 |
return spec |
| 121 |
|
| 122 |
|
| 123 |
ignores = set() |
| 124 |
|
| 125 |
|
| 126 |
def init(ignoreset): |
| 127 |
global ignores |
| 128 |
ignores = ignoreset |
| 129 |
|
| 130 |
|
| 131 |
def isenabled(): |
| 132 |
return not _deactivated and any( |
| 133 |
isinstance(finder, LazyFinder) for finder in sys.meta_path |
| 134 |
) |
| 135 |
|
| 136 |
|
| 137 |
def disable(): |
| 138 |
new_finders = [] |
| 139 |
for finder in sys.meta_path: |
| 140 |
new_finders.append( |
| 141 |
finder._finder if isinstance(finder, LazyFinder) else finder |
| 142 |
) |
| 143 |
sys.meta_path[:] = new_finders |
| 144 |
|
| 145 |
|
| 146 |
def enable(): |
| 147 |
new_finders = [] |
| 148 |
for finder in sys.meta_path: |
| 149 |
new_finders.append( |
| 150 |
LazyFinder(finder) if not isinstance(finder, LazyFinder) else finder |
| 151 |
) |
| 152 |
sys.meta_path[:] = new_finders |
| 153 |
|
| 154 |
|
| 155 |
@contextlib.contextmanager |
| 156 |
def deactivated(): |
| 157 |
# This implementation is a bit different from Python 2's. Python 3 |
| 158 |
# maintains a per-package finder cache in sys.path_importer_cache (see |
| 159 |
# PEP 302). This means that we can't just call disable + enable. |
| 160 |
# If we do that, in situations like: |
| 161 |
# |
| 162 |
# demandimport.enable() |
| 163 |
# ... |
| 164 |
# from foo.bar import mod1 |
| 165 |
# with demandimport.deactivated(): |
| 166 |
# from foo.bar import mod2 |
| 167 |
# |
| 168 |
# mod2 will be imported lazily. (The converse also holds -- whatever finder |
| 169 |
# first gets cached will be used.) |
| 170 |
# |
| 171 |
# Instead, have a global flag the LazyLoader can use. |
| 172 |
global _deactivated |
| 173 |
demandenabled = isenabled() |
| 174 |
if demandenabled: |
| 175 |
_deactivated = True |
| 176 |
try: |
| 177 |
yield |
| 178 |
finally: |
| 179 |
if demandenabled: |
| 180 |
_deactivated = False |