Debian Codegraph @

docs/guide/users/how-to/selectively-inspect.md

raw symbols SCIP
1 # Inspecting specific objects
2
3 Griffe by default parses and visits your code (static analysis) instead of importing it and inspecting objects in memory (dynamic analysis). There are various reasons why static analysis is generally a better approach, but sometimes it is insufficient to handle particularly dynamic objects. When this happens and Griffe cannot handle specific objects, you have a few solutions:
4
5 1. enable dynamic analysis for the whole package
6 2. write a Griffe extension that dynamically handles just the problematic objects
7 3. write a Griffe extension that statically handles the objects
8
9 This document will help you achieve point 2.
10
11 <!-- TODO:
12 > NOTE: **Try static analysis first?**
13 > We always recommend to try and handle things statically, so if you're interested, please check out these other documents:
14 >
15 > - link to doc
16 > - link to doc
17 -->
18
19 Enabling dynamic analysis for whole packages is [not recommended][forcing-dynamic-analysis-not-recommended], but it can be useful to do it once and check the results, to see if our dynamic analysis agent is able to handle your code natively. Whether it is or not is not very important, you will be able to move onto creating an extension that will selectively inspect the relevant objects in any case. It could just be a bit more difficult in the latter case, and if you have trouble writing the extension we invite you to create a [Q&A discussion](https://github.com/mkdocstrings/griffe/discussions/categories/q-a) to get guidance.
20
21 ---
22
23 Start by creating an extensions module (a simple Python file) somewhere in your repository, if you don't already have one. Within it, create an extension class:
24
25 ```python
26 import griffe
27
28
29 class InspectSpecificObjects(griffe.Extension):
30 """An extension to inspect just a few specific objects."""
31 ```
32
33 Make it accept configuration options by declaring an `__init__` method:
34
35 ```python hl_lines="7-8"
36 import griffe
37
38
39 class InspectSpecificObjects(griffe.Extension):
40 """An extension to inspect just a few specific objects."""
41
42 def __init__(self, objects: list[str]) -> None:
43 self.objects = objects
44 ```
45
46 Here we choose to store a list of strings, where each string is an object path, like `module.Class.method`. Feel free to store different values to help you filter objects according to your needs. For example, maybe you want to inspect all functions with a given label, in that case you could accept a single string which is the label name. Or you may want to inspect all functions decorated with a specific decorator, etc.
47
48 With this `__init__` method, users (or simply yourself) will be able to configure the extension by passing a list of object paths. You could also hard-code everything in the extension if you don't want or need to configure it.
49
50 Now that our extension accepts options, we implement its core functionality. We assume that the static analysis agent is able to see the objects we are interested in, and will actually create instances that represent them (Griffe objects). Therefore we hook onto the `on_instance` event, which runs each time a Griffe object is created.
51
52 ```python hl_lines="10-11"
53 import griffe
54
55
56 class InspectSpecificObjects(griffe.Extension):
57 """An extension to inspect just a few specific objects."""
58
59 def __init__(self, objects: list[str]) -> None:
60 self.objects = objects
61
62 def on_instance(self, *, obj: griffe.Object, **kwargs) -> None:
63 ...
64 ```
65
66 Check out the [available hooks][griffe.Extension] to see if there more appropriate hooks for your needs.
67
68 Lets now use our configuration option to decide whether to do something or skip:
69
70 ```python hl_lines="11-12"
71 import griffe
72
73
74 class InspectSpecificObjects(griffe.Extension):
75 """An extension to inspect just a few specific objects."""
76
77 def __init__(self, objects: list[str]) -> None:
78 self.objects = objects
79
80 def on_instance(self, *, obj: griffe.Object, **kwargs) -> None:
81 if obj.path not in self.objects:
82 return
83 ```
84
85 Now we know that only the objects we're interested in will be handled, so lets handle them.
86
87 ```python hl_lines="3 16-20"
88 import griffe
89
90 logger = griffe.get_logger("griffe_inspect_specific_objects") # (1)!
91
92
93 class InspectSpecificObjects(griffe.Extension):
94 """An extension to inspect just a few specific objects."""
95
96 def __init__(self, objects: list[str]) -> None:
97 self.objects = objects
98
99 def on_instance(self, *, obj: griffe.Object, **kwargs) -> None:
100 if obj.path not in self.objects:
101 return
102
103 try:
104 runtime_obj = griffe.dynamic_import(obj.path)
105 except ImportError as error:
106 logger.warning(f"Could not import {obj.path}: {error}") # (2)!
107 return
108 ```
109
110 1. We integrate with Griffe's logging (which also ensures integration with MkDocs' logging) by creating a logger. The name should look like a package name, with underscores.
111 2. We decide to log the exception as a warning (causing MkDocs builds to fail in `--strict` mode), but you could also log an error, or a debug message.
112
113 Now that we have a reference to our runtime object, we can use it to alter the Griffe object.
114
115 For example, we could use the runtime object's `__doc__` attribute, which could have been declared dynamically, to fix the Griffe object docstring:
116
117 ```python hl_lines="22-25"
118 import griffe
119
120 logger = griffe.get_logger("griffe_inspect_specific_objects")
121
122
123 class InspectSpecificObjects(griffe.Extension):
124 """An extension to inspect just a few specific objects."""
125
126 def __init__(self, objects: list[str]) -> None:
127 self.objects = objects
128
129 def on_instance(self, *, obj: griffe.Object, **kwargs) -> None:
130 if obj.path not in self.objects:
131 return
132
133 try:
134 runtime_obj = griffe.dynamic_import(obj.path)
135 except ImportError as error:
136 logger.warning(f"Could not import {obj.path}: {error}")
137 return
138
139 if obj.docstring:
140 obj.docstring.value = runtime_obj.__doc__
141 else:
142 obj.docstring = griffe.Docstring(runtime_obj.__doc__)
143 ```
144
145 Or we could alter the Griffe object parameters in case of functions, which could have been modified by a signature-changing decorator:
146
147 ```python hl_lines="1 23-27"
148 import inspect
149 import griffe
150
151 logger = griffe.get_logger("griffe_inspect_specific_objects")
152
153
154 class InspectSpecificObjects(griffe.Extension):
155 """An extension to inspect just a few specific objects."""
156
157 def __init__(self, objects: list[str]) -> None:
158 self.objects = objects
159
160 def on_instance(self, *, obj: griffe.Object, **kwargs) -> None:
161 if obj.path not in self.objects:
162 return
163
164 try:
165 runtime_obj = griffe.dynamic_import(obj.path)
166 except ImportError as error:
167 logger.warning(f"Could not import {obj.path}: {error}")
168 return
169
170 # Update default values modified by decorator.
171 signature = inspect.signature(runtime_obj)
172 for param in signature.parameters:
173 if param.name in obj.parameters:
174 obj.parameters[param.name].default = repr(param.default)
175 ```
176
177 We could also entirely replace the Griffe object obtained from static analysis by the same one obtained from dynamic analysis:
178
179
180 ```python hl_lines="14-25"
181 import griffe
182
183
184 class InspectSpecificObjects(griffe.Extension):
185 """An extension to inspect just a few specific objects."""
186
187 def __init__(self, objects: list[str]) -> None:
188 self.objects = objects
189
190 def on_instance(self, *, obj: griffe.Object, **kwargs) -> None:
191 if obj.path not in self.objects:
192 return
193
194 inspected_module = griffe.inspect(obj.module.path, filepath=obj.filepath)
195 obj.parent.set_member(obj.name, inspected_module[obj.name]) # (1)!
196 ```
197
198 1. This assumes the object we're interested in is declared at the module level.