0
# Loaders
1
2
High-level functions for loading Python packages and modules from different sources. Loaders orchestrate the analysis process using both static analysis (AST parsing) and dynamic analysis (runtime inspection) to extract comprehensive API information.
3
4
## Capabilities
5
6
### Standard Package Loading
7
8
Load a Python package or module from the current environment.
9
10
```python { .api }
11
def load(
12
objspec: str | Path | None = None,
13
/,
14
*,
15
submodules: bool = True,
16
try_relative_path: bool = True,
17
extensions: Extensions | None = None,
18
search_paths: Sequence[str | Path] | None = None,
19
docstring_parser: DocstringStyle | Parser | None = None,
20
docstring_options: dict[str, Any] | None = None,
21
lines_collection: LinesCollection | None = None,
22
modules_collection: ModulesCollection | None = None,
23
allow_inspection: bool = True,
24
force_inspection: bool = False,
25
store_source: bool = True,
26
find_stubs_package: bool = False,
27
resolve_aliases: bool = False,
28
resolve_external: bool | None = None,
29
resolve_implicit: bool = False,
30
) -> Object | Alias:
31
"""
32
Load and return a Griffe object from a module specification.
33
34
Main high-level function for loading API data from Python packages.
35
Supports both static analysis via AST parsing and dynamic analysis
36
via runtime inspection.
37
38
Args:
39
objspec: Module specification (e.g., 'requests', 'requests.api.get') or Path object
40
submodules: Whether to load submodules automatically
41
try_relative_path: Whether to try loading as relative path
42
extensions: Extensions to use during loading
43
search_paths: Additional paths to search for modules (Sequence instead of list)
44
docstring_parser: Parser for docstrings (DocstringStyle enum or Parser)
45
docstring_options: Options passed to docstring parser
46
lines_collection: Collection to store source lines
47
modules_collection: Collection to store loaded modules
48
allow_inspection: Whether to allow runtime inspection fallback
49
force_inspection: Whether to force runtime inspection even when AST available
50
store_source: Whether to store source code in objects
51
find_stubs_package: Whether to search for stub packages
52
resolve_aliases: Whether to resolve aliases immediately
53
resolve_external: Whether to resolve external aliases
54
resolve_implicit: Whether to resolve implicit aliases
55
56
Returns:
57
Object | Alias: The loaded module, class, function, attribute, or alias
58
59
Raises:
60
LoadingError: If the module cannot be loaded
61
NameResolutionError: If the object specification cannot be resolved
62
"""
63
```
64
65
### Git-Based Loading
66
67
Load a package from a specific Git reference (commit, branch, or tag).
68
69
```python { .api }
70
def load_git(
71
objspec: str,
72
ref: str = "HEAD",
73
*,
74
repo: str | Path = ".",
75
**load_kwargs: Any,
76
) -> Object:
77
"""
78
Load and return a module from a specific Git reference.
79
80
Allows loading API data from a specific commit, branch, or tag in a Git
81
repository. Useful for comparing different versions or analyzing historical APIs.
82
83
Args:
84
objspec: Module specification to load
85
ref: Git reference (commit hash, branch name, or tag)
86
repo: Path to the Git repository (default: current directory)
87
**load_kwargs: Additional arguments passed to load()
88
89
Returns:
90
Object: The loaded object from the specified Git reference
91
92
Raises:
93
GitError: If Git operations fail
94
LoadingError: If the module cannot be loaded from the Git reference
95
96
Examples:
97
Load from a specific tag:
98
>>> old_api = griffe.load_git("mypackage", ref="v1.0.0")
99
100
Load from a branch:
101
>>> feature_api = griffe.load_git("mypackage", ref="feature-branch")
102
103
Load from a commit:
104
>>> commit_api = griffe.load_git("mypackage", ref="abc123def")
105
"""
106
```
107
108
### PyPI Package Loading
109
110
Load a package from PyPI (Python Package Index) at a specific version.
111
112
```python { .api }
113
def load_pypi(
114
package: str,
115
distribution: str,
116
version_spec: str,
117
*,
118
submodules: bool = True,
119
extensions: Extensions | None = None,
120
search_paths: Sequence[str | Path] | None = None,
121
docstring_parser: DocstringStyle | Parser | None = None,
122
docstring_options: dict[str, Any] | None = None,
123
lines_collection: LinesCollection | None = None,
124
modules_collection: ModulesCollection | None = None,
125
allow_inspection: bool = True,
126
force_inspection: bool = False,
127
find_stubs_package: bool = False,
128
) -> Object | Alias:
129
"""
130
Load and return a module from a specific package version downloaded using pip.
131
132
Enables loading API data from PyPI packages at specific versions.
133
Requires the 'pypi' extra: pip install griffe[pypi]
134
135
Args:
136
package: The package import name
137
distribution: The distribution name
138
version_spec: The version specifier to use when installing with pip
139
submodules: Whether to recurse on the submodules
140
extensions: The extensions to use
141
search_paths: The paths to search into
142
docstring_parser: The docstring parser to use
143
docstring_options: The docstring parser options
144
lines_collection: A collection of source code lines
145
modules_collection: A collection of modules
146
allow_inspection: Whether to allow inspecting modules when visiting them is not possible
147
force_inspection: Whether to force using dynamic analysis when loading data
148
find_stubs_package: Whether to search for stubs packages
149
150
Returns:
151
Object | Alias: The loaded object from the PyPI package
152
153
Raises:
154
LoadingError: If the package cannot be downloaded or loaded
155
156
Examples:
157
Load latest version:
158
>>> package = griffe.load_pypi("requests")
159
160
Load specific version:
161
>>> old_django = griffe.load_pypi("django", "3.2.0")
162
163
Load with version constraints:
164
>>> fastapi = griffe.load_pypi("fastapi", ">=0.68.0,<1.0.0")
165
"""
166
```
167
168
### Loader Class
169
170
Advanced loader class for fine-grained control over the loading process.
171
172
```python { .api }
173
class GriffeLoader:
174
"""
175
Main loader class that handles the loading process.
176
177
Provides configurable options for extensions, search paths,
178
docstring parsing, and more advanced loading scenarios.
179
"""
180
181
def __init__(
182
self,
183
*,
184
search_paths: Sequence[str | Path] | None = None,
185
docstring_parser: Parser | None = None,
186
docstring_options: dict[str, Any] | None = None,
187
lines_collection: LinesCollection | None = None,
188
modules_collection: ModulesCollection | None = None,
189
allow_inspection: bool = True,
190
store_source: bool = True,
191
extensions: Extensions | None = None,
192
) -> None:
193
"""
194
Initialize the loader.
195
196
Args:
197
search_paths: Directories to search for modules
198
docstring_parser: Parser for processing docstrings
199
docstring_options: Configuration for docstring parsing
200
lines_collection: Collection for source code lines
201
modules_collection: Collection for loaded modules
202
allow_inspection: Enable runtime inspection fallback
203
store_source: Store source code in loaded objects
204
extensions: Extensions to apply during loading
205
"""
206
207
def load(
208
self,
209
objspec: str,
210
*,
211
try_relative_path: bool = True,
212
resolve_aliases: bool = False,
213
resolve_external: bool | None = None,
214
resolve_implicit: bool = False,
215
) -> Object:
216
"""
217
Load an object using this loader's configuration.
218
219
Args:
220
objspec: Object specification to load
221
try_relative_path: Try loading as relative path
222
resolve_aliases: Resolve aliases immediately
223
resolve_external: Resolve external aliases
224
resolve_implicit: Resolve implicit aliases
225
226
Returns:
227
Object: The loaded object
228
"""
229
230
def load_module(
231
self,
232
module_name: str,
233
filepath: str | Path | None = None,
234
parent: Module | None = None,
235
) -> Module:
236
"""
237
Load a specific module.
238
239
Args:
240
module_name: Name of the module to load
241
filepath: Path to the module file (optional)
242
parent: Parent module (for submodules)
243
244
Returns:
245
Module: The loaded module
246
"""
247
```
248
249
## Usage Examples
250
251
### Basic Loading
252
253
```python
254
import griffe
255
256
# Load a package
257
requests_api = griffe.load("requests")
258
print(f"Package: {requests_api.name}")
259
print(f"Modules: {list(requests_api.modules.keys())}")
260
261
# Load a specific function
262
get_function = griffe.load("requests.api.get")
263
print(f"Function: {get_function.name}")
264
print(f"Parameters: {[p.name for p in get_function.parameters]}")
265
```
266
267
### Version Comparison
268
269
```python
270
import griffe
271
272
# Compare current version with previous Git tag
273
old_version = griffe.load_git("mypackage", ref="v1.0.0")
274
current_version = griffe.load("mypackage")
275
276
# Compare PyPI versions
277
old_pypi = griffe.load_pypi("django", "3.2.0")
278
new_pypi = griffe.load_pypi("django", "4.0.0")
279
280
breakages = griffe.find_breaking_changes(old_pypi, new_pypi)
281
for breakage in breakages:
282
print(f"Breaking change: {breakage}")
283
```
284
285
### Advanced Loading Configuration
286
287
```python
288
import griffe
289
from griffe import Extensions, Parser
290
291
# Configure custom loader
292
extensions = griffe.load_extensions(["dataclasses"])
293
loader = griffe.GriffeLoader(
294
docstring_parser=Parser.GOOGLE,
295
docstring_options={"style": "google"},
296
extensions=extensions,
297
allow_inspection=False, # Static analysis only
298
store_source=True,
299
)
300
301
# Load with custom configuration
302
package = loader.load("mypackage")
303
304
# Configure search paths
305
loader_with_paths = griffe.GriffeLoader(
306
search_paths=["src", "lib", "/opt/custom-packages"]
307
)
308
custom_package = loader_with_paths.load("custom_module")
309
```
310
311
### Error Handling
312
313
```python
314
import griffe
315
from griffe import LoadingError, NameResolutionError, GitError
316
317
try:
318
package = griffe.load("nonexistent_package")
319
except LoadingError as e:
320
print(f"Failed to load package: {e}")
321
322
try:
323
git_package = griffe.load_git("mypackage", ref="invalid-ref")
324
except GitError as e:
325
print(f"Git error: {e}")
326
327
try:
328
specific_func = griffe.load("mypackage.nonexistent.function")
329
except NameResolutionError as e:
330
print(f"Cannot resolve name: {e}")
331
```
332
333
## Types
334
335
```python { .api }
336
from pathlib import Path
337
from typing import Any, Sequence
338
from enum import Enum
339
340
class Parser(Enum):
341
"""Docstring parser types."""
342
AUTO = "auto"
343
GOOGLE = "google"
344
NUMPY = "numpy"
345
SPHINX = "sphinx"
346
347
# Collection types
348
class LinesCollection:
349
"""Collection for managing source code lines."""
350
351
class ModulesCollection:
352
"""Collection for managing loaded modules."""
353
354
class Extensions:
355
"""Container for Griffe extensions."""
356
```