Debian Codegraph @

src/globus_sdk/_internal/lazy_import.py

raw
1 """
2 Tooling for an extremely simple lazy-import system, based on inspection of
3 pyi files.
4
5 Given a base module name (used for lookup and error messages) and the name
6 of a pyi file, we can use the pyi file to lookup import locations.
7
8 i.e. Given
9
10 foo.py
11 foo.pyi
12 bar.py
13
14 then if `foo.pyi` has an import `from .bar import BarType`, it is possible to
15 *read* `foo.pyi` at runtime and use that information to load
16 `BarType` from `bar`.
17
18
19 Rationale
20 ---------
21
22 Why use this type of lazy importer?
23
24 The major goals are:
25 - type information is still available to type checkers (and other tools like IDEs)
26 - we minimize manual duplication of names
27 - we minimize specialized knowledge needed to update our package exports
28 - the lazy importer itself is easy to maintain and update
29
30 ``.pyi`` type stubs are designed for use with type checkers. The data format choice here
31 is "regular type stubs". We treat it as runtime data, which is a bit unusual, but we
32 are guaranteed that `mypy` and other tools can understand it without issue.
33
34 We reduce duplication with this technique, and the content in the ``.pyi`` file should
35 be easy for most developers to read and modify.
36 """
37
38 from __future__ import annotations
39
40 import ast
41 import sys
42 import typing as t
43
44
45 def load_all_tuple(modname: str, pyi_filename: str) -> tuple[str, ...]:
46 """
47 Load the __all__ tuple from a ``.pyi`` file.
48
49 This should run before the getattr and dir implementations are defined, as those use
50 the runtime ``__all__`` tuple.
51
52 :param modname: The name of the module doing the load. Usually ``__name__``.
53 :param pyi_filename: The name of the ``pyi`` file relative to ``modname``.
54 ``importlib.resources`` will use both of these fields to load the ``pyi``
55 data, so the file must be in package metadata.
56 """
57 return _ParsedPYIData.load(modname, pyi_filename).all_names
58
59
60 def default_getattr_implementation(
61 modname: str, pyi_filename: str
62 ) -> t.Callable[[str], t.Any]:
63 """
64 Build an implementation of module ``__getattr__`` given the module name and
65 the pyi file which will drive lazy imports.
66
67 :param modname: The name of the module where ``__getattr__`` is being added.
68 Usually ``__name__``.
69 :param pyi_filename: The name of the ``pyi`` file relative to ``modname``.
70 ``importlib.resources`` will use both of these fields to load the ``pyi``
71 data, so the file must be in package metadata.
72 """
73 module_object = sys.modules[modname]
74 all_tuple = module_object.__all__
75
76 def getattr_implementation(name: str) -> t.Any:
77 if name in all_tuple:
78 value = load_attr(modname, pyi_filename, name)
79 setattr(module_object, name, value)
80 return value
81
82 raise AttributeError(f"module {modname} has no attribute {name}")
83
84 return getattr_implementation
85
86
87 def default_dir_implementation(modname: str) -> t.Callable[[], list[str]]:
88 """
89 Build an implementation of module ``__dir__`` given the module name.
90
91 :param modname: The name of the module where ``__dir__`` is being added.
92 Usually ``__name__``.
93 """
94 # dir(globus_sdk) should include everything exported in __all__
95 # as well as some explicitly selected attributes from the default dir() output
96 # on a module
97 #
98 # see also:
99 # https://discuss.python.org/t/how-to-properly-extend-standard-dir-search-with-module-level-dir/4202
100 module_object = sys.modules[modname]
101 all_tuple = module_object.__all__
102
103 def dir_implementation() -> list[str]:
104 return list(all_tuple) + [
105 # __all__ itself can be inspected
106 "__all__",
107 # useful to figure out where a package is installed
108 "__file__",
109 "__path__",
110 ]
111
112 return dir_implementation
113
114
115 def load_attr(modname: str, pyi_filename: str, attrname: str) -> t.Any:
116 """
117 Execute an import of a single attribute in the manner that it was declared in a
118 ``.pyi`` file.
119
120 The import in the pyi data is expected to be a `from x import y` statement.
121 Only the specific attribute will be imported, even if the pyi declares multiple
122 imports from the same module.
123
124 :param modname: The name of the module importing the attribute.
125 Usually ``__name__``.
126 :param pyi_filename: The name of the ``pyi`` file relative to ``modname``.
127 ``importlib.resources`` will use both of these fields to load the ``pyi``
128 data, so the file must be in package metadata.
129 :param attrname: The name of the attribute to load.
130 """
131 import importlib
132
133 attr_source = find_source_module(modname, pyi_filename, attrname)
134 attr_source_mod = importlib.import_module(attr_source, modname)
135 return getattr(attr_source_mod, attrname)
136
137
138 def find_source_module(modname: str, pyi_filename: str, attrname: str) -> str:
139 """
140 Find the source module which provides an attribute, based on a declared import in a
141 ``.pyi`` file.
142
143 The ``.pyi`` data will be parsed as AST and scanned for an appropriate import.
144
145 :param modname: The name of the module importing the attribute.
146 Usually ``__name__``.
147 :param pyi_filename: The name of the ``pyi`` file relative to ``modname``.
148 ``importlib.resources`` will use both of these fields to load the ``pyi``
149 data, so the file must be in package metadata.
150 :param attrname: The name of the attribute to load.
151 """
152 parsed = _ParsedPYIData.load(modname, pyi_filename)
153 return parsed.module_for_attr(attrname)
154
155
156 class _ParsedPYIData:
157 _CACHE: dict[tuple[str, str], _ParsedPYIData] = {}
158
159 @classmethod
160 def load(cls, module_name: str, pyi_filename: str) -> _ParsedPYIData:
161 if (module_name, pyi_filename) not in cls._CACHE:
162 cls._CACHE[(module_name, pyi_filename)] = cls(module_name, pyi_filename)
163 return cls._CACHE[(module_name, pyi_filename)]
164
165 def __init__(self, module_name: str, pyi_filename: str) -> None:
166 self.module_name = module_name
167 self.pyi_filename = pyi_filename
168 self._ast = _parse_pyi_ast(module_name, pyi_filename)
169
170 self._import_attr_map: dict[str, str] = {}
171 self._all_names: list[str] = []
172
173 self._load()
174
175 @property
176 def all_names(self) -> tuple[str, ...]:
177 return tuple(self._all_names)
178
179 def module_for_attr(self, attrname: str) -> str:
180 if attrname not in self._import_attr_map:
181 raise LookupError(
182 f"Could not find import of '{attrname}' in '{self.module_name}'."
183 )
184 return self._import_attr_map[attrname]
185
186 def _load(self) -> None:
187 for statement in self._ast.body:
188 self._load_statement(statement)
189
190 def _load_statement(self, statement: ast.AST) -> None:
191 if isinstance(statement, ast.ImportFrom):
192 # type ignore the possibility of 'import_from.module == None'
193 # as it's not possible from parsed code
194 module_name = ( # type: ignore[operator]
195 "." * statement.level
196 ) + statement.module
197
198 for alias in statement.names:
199 attr_name = alias.name if alias.asname is None else alias.asname
200 self._import_attr_map[attr_name] = module_name
201 elif isinstance(statement, ast.Assign):
202 if len(statement.targets) != 1:
203 return
204 target = statement.targets[0]
205 if not isinstance(target, ast.Name):
206 return
207 if target.id != "__all__":
208 return
209 if not isinstance(statement.value, ast.Tuple):
210 raise ValueError(
211 f"While reading '__all__' for '{self.module_name}' from "
212 f"'{self.pyi_filename}', '__all__' was not a tuple "
213 )
214 for element in statement.value.elts:
215 if not isinstance(element, ast.Constant) or not isinstance(
216 element.value, str
217 ):
218 continue
219 self._all_names.append(element.value)
220
221
222 def _parse_pyi_ast(anchor_module_name: str, pyi_filename: str) -> ast.Module:
223 import importlib.resources
224
225 source = (
226 importlib.resources.files(anchor_module_name) # pylint: disable=no-member
227 .joinpath(pyi_filename)
228 .read_bytes()
229 )
230 return ast.parse(source)