Debian Codegraph @

docs/guide/users/navigating.md

raw symbols SCIP
1 # Navigating APIs
2
3 Griffe loads API data into data models. These models provide various attributes and methods to access or update specific fields. The different models are:
4
5 - [`Module`][griffe.Module], representing Python modules;
6 - [`Class`][griffe.Class], representing Python classes;
7 - [`Function`][griffe.Function], representing Python functions and class methods;
8 - [`Attribute`][griffe.Attribute], representing object attributes that weren't identified as modules, classes or functions;
9 - [`Type Alias`][griffe.TypeAlias], representing Python type aliases;
10 - [`Alias`][griffe.Alias], representing indirections such as imported objects or class members inherited from parent classes.
11
12 When [loading an object](loading.md), Griffe will give you back an instance of one of these models. A few examples:
13
14 ```python
15 >>> import griffe
16 >>> type(griffe.load("markdown"))
17 <class 'griffe._internal.models.Module'>
18 >>> type(griffe.load("markdown.core.Markdown"))
19 <class 'griffe._internal.models.Class'>
20 >>> type(griffe.load("markdown.Markdown"))
21 <class 'griffe._internal.models.Alias'>
22 >>> type(griffe.load("markdown.core.markdown"))
23 <class 'griffe._internal.models.Function'>
24 >>> type(griffe.load("markdown.markdown"))
25 <class 'griffe._internal.models.Alias'>
26 >>> type(griffe.load("markdown.Markdown.references"))
27 <class 'griffe._internal.models.Attribute'>
28 ```
29
30 However deep the object is, Griffe loads the entire package. It means that in all the cases above, Griffe loaded the whole `markdown` package. The model instance Griffe gives you back is therefore part of a tree that you can navigate.
31
32 ## Moving up: parents
33
34 Each object holds a reference to its [`parent`][griffe.Object.parent] (except for the top-level module, for which the parent is `None`). Shortcuts are provided to climb up directly to the parent [`module`][griffe.Object.module], or the top-level [`package`][griffe.Object.package]. As we have seen in the [Loading chapter](loading.md), Griffe stores all loaded modules in a modules collection; this collection can be accessed too, through the [`modules_collection`][griffe.Object.modules_collection] attribute.
35
36 ## Moving down: members
37
38 To access an object's members, there are a few options:
39
40 - Access to regular members through the [`members`][griffe.Object.members] attribute, which is a dictionary. The keys are member names, the values are Griffe models.
41
42 ```pycon
43 >>> import griffe
44 >>> markdown = griffe.load("markdown")
45 >>> markdown.members["Markdown"]
46 Alias('Markdown', 'markdown.core.Markdown')
47 >>> markdown.members["core"].members["Markdown"]
48 Class('Markdown', 46, 451)
49 ```
50
51 - Access to both regular and inherited members through the [`all_members`][griffe.Object.all_members] attribute, which is a dictionary again. See [Inherited members](#inherited-members).
52
53 - Convenient dictionary-like item access, thanks to the subscript syntax `[]`. With this syntax, you will not only be able to chain accesses, but also merge them into a single access by using dot-separated paths to objects:
54
55 ```pycon
56 >>> import griffe
57 >>> markdown = griffe.load("markdown")
58 >>> markdown["core"]["Markdown"] # chained access
59 Class('Markdown', 46, 451)
60 >>> markdown["core.Markdown"] # merged access
61 Class('Markdown', 46, 451)
62 ```
63
64 The dictionary-like item access also accepts tuples of strings. So if for some reason you don't have a string equal to `"core.Markdown"` but a tuple equal to `("core", "Markdown")` (for example obtained from splitting another string), you can use it too:
65
66 ```pycon
67 >>> import griffe
68 >>> markdown = griffe.load("markdown")
69 >>> markdown[("core", "Markdown")] # tuple access
70 Class('Markdown', 46, 451)
71 >>> # Due to the nature of the subscript syntax,
72 >>> # you can even use implicit tuples.
73 >>> markdown["core", "Markdown"]
74 Class('Markdown', 46, 451)
75 ```
76
77 - Less convenient, but safer access to members while the object tree is being built (while a package is still being loaded), using the [`get_member()`][griffe.GetMembersMixin.get_member] method.
78
79 ```pycon
80 >>> import griffe
81 >>> markdown = griffe.load("markdown")
82 >>> markdown.get_member("core.Markdown")
83 Class('Markdown', 46, 451)
84 ```
85
86 In particular, Griffe extensions should always use `get_member` instead of the subscript syntax `[]`. The `get_member` method only looks into regular members, while the subscript syntax looks into inherited members too (for classes), which cannot be correctly computed until a package is fully loaded (which is generally not the case when an extension is running).
87
88 - In addition to this, models provide the [`attributes`][griffe.Object.attributes], [`functions`][griffe.Object.functions], [`classes`][griffe.Object.classes], [`type_aliases`][griffe.Object.type_aliases] or [`modules`][griffe.Object.modules] attributes, which return only members of the corresponding kind. These attributes are computed dynamically each time (they are Python properties).
89
90 The same way members are accessed, they can also be set:
91
92 - Dictionary-like item assignment: `markdown["thing"] = ...`, also supporting dotted-paths and string tuples. This will (re)assign only regular members: inherited members (classes only) are re-computed everytime they are accessed.
93 - Safer method for extensions: `markdown.set_member("thing", ...)`, also supporting dotted-paths and string tuples.
94 - Regular member assignment: `markdown.members["thing"] = ...`. **This is not recommended, as the assigned member's `parent` attribute will not be automatically updated.**
95
96 ...and deleted:
97
98 - Dictionary-like item deletion: `del markdown["thing"]`, also supporting dotted-paths and string tuples. This will delete only regular members: inherited members (classes only) are re-computed everytime they are accessed.
99 - Safer method for extensions: `markdown.del_member("thing")`, also supporting dotted-paths and string tuples.
100 - Regular member deletion: `del markdown.members["thing"]`. **This is not recommended, as the [`aliases`][griffe.Object.aliases] attribute of other objects in the tree will not be automatically updated.**
101
102 ### Inherited members
103
104 Griffe supports class inheritance, both when visiting and inspecting modules.
105
106 To access members of a class that are inherited from base classes, use the [`inherited_members`][griffe.Object.inherited_members] attribute. Everytime you access inherited members, the base classes of the given class will be resolved, then the MRO (Method Resolution Order) will be computed for these base classes, and a dictionary of inherited members will be built. Make sure to store the result in a variable to avoid re-computing it everytime (you are responsible for the caching part). Also make sure to only access `inherited_members` once everything is loaded by Griffe, to avoid computing things too early. Don't try to access inherited members in extensions, while visiting or inspecting modules.
107
108 Inherited members are aliases that point at the corresponding members in parent classes. These aliases will have their [`inherited`][griffe.Alias.inherited] attribute set to true.
109
110 **Important:** only classes from already loaded packages will be used when computing inherited members. This gives users control over how deep into inheritance to go, by pre-loading packages from which you want to inherit members. For example, if `package_c.ClassC` inherits from `package_b.ClassB`, itself inheriting from `package_a.ClassA`, and you want to load `ClassB` members only:
111
112 ```python
113 import griffe
114
115 loader = griffe.GriffeLoader()
116 # note that we don't load package_a
117 loader.load("package_b")
118 loader.load("package_c")
119 ```
120
121 If a base class cannot be resolved during computation of inherited members, Griffe logs a DEBUG message.
122
123 If you want to access all members at once (both declared and inherited), use the [`all_members`][griffe.Object.all_members] attribute. If you want to access only declared members, use the [`members`][griffe.Object] attribute.
124
125 Accessing the [`attributes`][griffe.Object.attributes], [`functions`][griffe.Object.functions], [`classes`][griffe.Object.classes], [`type_aliases`][griffe.Object.type_aliases] or [`modules`][griffe.Object.modules] attributes will trigger inheritance computation, so make sure to only access them once everything is loaded by Griffe. Don't try to access inherited members in extensions, while visiting or inspecting modules.
126
127 #### Limitations
128
129 Currently, there are three limitations to our class inheritance support:
130
131 1. when visiting (static analysis), some objects are not yet properly recognized as classes, for example named tuples. If you inherit from a named tuple, its members won't be added to the inherited members of the inheriting class.
132
133 ```python
134 MyTuple = namedtuple("MyTuple", "attr1 attr2")
135
136
137 class MyClass(MyTuple):
138 ...
139 ```
140
141 2. when visiting (static analysis), subclasses using the same name as one of their parent classes will prevent Griffe from computing the MRO and therefore the inherited members. To circumvent that, give a different name to your subclass:
142
143 ```python
144 from package import SomeClass
145
146
147 # instead of
148 class SomeClass(SomeClass):
149 ...
150
151
152 # do
153 class SomeOtherClass(SomeClass):
154 ...
155 ```
156
157 3. when inspecting (dynamic analysis), ephemeral base classes won't be resolved, and therefore their members won't appear in child classes. To circumvent that, assign these dynamic classes to variables:
158
159 ```python
160 # instead of
161 class MyClass(namedtuple("MyTuple", "attr1 attr2")):
162 ...
163
164
165 # do
166 MyTuple = namedtuple("MyTuple", "attr1 attr2")
167
168
169 class MyClass(MyTuple):
170 ...
171 ```
172
173 We will try to lift these limitations in the future.
174
175 ## Aliases
176
177 Aliases represent indirections, such as objects imported from elsewhere, attributes, or methods inherited from parent classes. They are pointers to the object they represent. The path of the object they represent is stored in their [`target_path`][griffe.Alias.target_path] attribute. Once they are resolved, the target object can be accessed through their [`target`][griffe.Alias.target] attribute.
178
179 Aliases can be found in objects' members. Each object can also access its own aliases (the aliases pointing at it) through its [`aliases`][griffe.Object.aliases] attribute. This attribute is a dictionary whose keys are the aliases paths and values are the aliases themselves.
180
181 Most of the time, aliases simply act as proxies to their target objects. For example, accessing the `docstring` of an alias will simply return the docstring of the object it targets.
182
183 Accessing fields on aliases will trigger their resolution. If they are already resolved (their `target` attribute is set to the target object), the field is returned. If they are not resolved, their target path will be looked up in the modules collection, and if it is found, the object at this location will be assigned to the alias' `target` attribute. If it isn't found, an [`AliasResolutionError`][griffe.AliasResolutionError] exception will be raised.
184
185 Since merely accessing an alias field can raise an exception, it is often useful to check if an object is an alias before accessing its fields. There are multiple ways to check if an object is an alias:
186
187 - using the `is_alias` boolean ([`Object.is_alias`][griffe.Object.is_alias], [`Alias.is_alias`][griffe.Alias.is_alias]), which won't trigger resolution
188 - using `isinstance` to check if the object is an instance of [`Alias`][griffe.Alias]
189
190 ```pycon
191 >>> import griffe
192 >>> load = griffe.load("griffe.load")
193 >>> load.is_alias
194 True
195 >>> isinstance(load, griffe.Alias)
196 True
197 ```
198
199 The [`kind`][griffe.Alias.kind] of an alias will only return [`ALIAS`][griffe.Kind.ALIAS] if the alias is not resolved and cannot be resolved within the current modules collection.
200
201 You can of course also catch any raised exception with a regular try/except block:
202
203 ```python
204 try:
205 print(obj.source)
206 except griffe.AliasResolutionError:
207 pass
208 ```
209
210 To check if an alias is already resolved, you can use its [`resolved`][griffe.Alias.resolved] attribute.
211
212 ### Alias chains
213
214 Aliases can be chained. For example, if module `a` imports `X` from module `b`, which itself imports `X` from module `c`, then `a.X` is an alias to `b.X` which is an alias to `c.X`: `a.X` -> `b.X` -> `c.X`. To access the final target directly, you can use the [`final_target`][griffe.Alias.final_target] attribute. Most alias properties that act like proxies actually fetch the final target rather than the next one to return the final field.
215
216 Sometimes, when a package makes use of complicated imports (wildcard imports from parents and submodules), or when runtime objects are hard to inspect, it is possible to end up with a cyclic chain of aliases. You could for example end up with a chain like `a.X` -> `b.X` -> `c.X` -> `a.X`. In this case, the alias *cannot* be resolved, since the chain goes in a loop. Griffe will raise a [`CyclicAliasError`][griffe.CyclicAliasError] when trying to resolve such cyclic chains.
217
218 Aliases chains are never partially resolved: either they are resolved down to their final target, or none of their links are resolved.
219
220 ## Object kind
221
222 The kind of an object (module, class, function, attribute, type alias or alias) can be obtained in several ways.
223
224 - With the [`kind`][griffe.Object.kind] attribute and the [`Kind`][griffe.Kind] enumeration: `obj.kind is Kind.MODULE`.
225
226 - With the [`is_kind()`][griffe.Object.is_kind] method:
227
228 - `obj.is_kind(Kind.MODULE)`
229 - `obj.is_kind("class")`
230 - `obj.is_kind({"function", Kind.ATTRIBUTE})`
231
232 When given a set of kinds, the method returns true if the object is of one of the given kinds.
233
234 - With the [`is_module`][griffe.Object.is_module], [`is_class`][griffe.Object.is_class], [`is_function`][griffe.Object.is_function], [`is_attribute`][griffe.Object.is_attribute], [`is_type_alias`][griffe.Object.is_type_alias], and [`is_alias`][griffe.Object.is_alias] attributes.
235
236 Additionally, it is possible to check if an object is a sub-kind of module, with the following attributes:
237
238 - [`is_init_module`][griffe.Object.is_init_module], for `__init__.py` modules
239 - [`is_package`][griffe.Object.is_package], for top-level packages
240 - [`is_subpackage`][griffe.Object.is_subpackage], for non-top-level packages
241 - [`is_namespace_package`][griffe.Object.is_namespace_package], for top-level [namespace packages](https://packaging.python.org/en/latest/guides/packaging-namespace-packages/)
242 - [`is_namespace_subpackage`][griffe.Object.is_namespace_subpackage], for non-top-level namespace packages
243
244 Finally, additional [`labels`][griffe.Object.labels] are attached to objects to further specify their kind. The [`has_labels()`][griffe.Object.has_labels] method can be used to check if an object has several specific labels.
245
246 ## Object location
247
248 An object is identified by its [`path`][griffe.Object.path], which is its location in the object tree. The path is composed of all the parent names and the object name, separated by dots, for example `mod.Class.meth`. This `path` is the [`canonical_path`][griffe.Object.canonical_path] on regular objects. For aliases however, the `path` is *where they are imported* while the canonical path is *where they come from*. Example:
249
250 ```python
251 # pkg1.py
252 from pkg2 import A as B
253 ```
254
255 ```pycon
256 >>> import griffe
257 >>> B = griffe.load("pkg1.B")
258 >>> B.path
259 'pkg1.B'
260 >>> B.canonical_path
261 'pkg2.A'
262 ```
263
264 ### Source
265
266 Information on the actual source code of objects is available through the following attributes:
267
268 - [`filepath`][griffe.Object.filepath], the absolute path to the module the object appears in, for example `~/project/src/pkg/mod.py`
269 - [`relative_filepath`][griffe.Object.relative_filepath], the relative path to the module, compared to the current working directory, for example `src/pkg/mod.py`
270 - [`relative_package_filepath`][griffe.Object.relative_package_filepath], the relative path to the module, compared to the parent of the top-level package, for example `pkg/mod.py`
271 - [`lineno`][griffe.Object.lineno] and [`endlineno`][griffe.Object.endlineno], the starting and ending line numbers of the object in the source
272 - [`lines`][griffe.Object.lines], the lines of code defining the object (or importing the alias)
273 - [`source`][griffe.Object.source], the source lines concatenated as a single multiline string
274
275 Each object holds a reference to a [`lines_collection`][griffe.Object.lines_collection]. Similar to the modules collection, this lines collection is a dictionary whose keys are module file-paths and values are their contents as list of lines. The lines collection is populated by the loader.
276
277 ## Object visibility
278
279 Each object has fields that are related to their visibility within the API.
280
281 - [`is_public`][griffe.Object.is_public]: whether this object is public (destined to be consumed by your users). For module-level objects, Griffe considers that the object is public if:
282
283 - it is listed in its parent module's `__all__` attribute
284 - or if its parent module does not declare `__all__`, and the object doesn't have a private name, and the object is not imported from elsewhere
285
286 ```python
287 # package1/__init__.py
288 from package2 import A # not public
289 from package1 import submodule # not public
290
291 b = 0 # public
292 _c = 1 # not public
293 __d = 2 # not public
294
295 def __getattr__(name: str): # public
296 ...
297 ```
298
299 For class-level objects, Griffe considers that the object is public if the object doesn't have a private name, and the object is not imported from elsewhere.
300
301 ```python
302 # package1/__init__.py
303 class A:
304 from package1.module import X # not public
305 from package2 import Y # not public
306
307 b = 0 # public
308 _c = 1 # not public
309 __d = 2 # not public
310
311 def __eq__(self, other): # public
312 ...
313 ```
314
315 - [`is_deprecated`][griffe.Object.is_deprecated]: whether this object is deprecated and shouldn't be used.
316
317 - [`is_special`][griffe.Object.is_special]: whether this object has a special name like `__special__`
318
319 - [`is_private`][griffe.Object.is_private]: whether this object has a private name like `_private` or `__private`, but not `__special__`
320
321 - [`is_class_private`][griffe.Object.is_class_private]: whether this object has a class-private name like `__private` and is a member of a class
322
323 Since `is_private` only checks the name of the object, it is not mutually exclusive with `is_public`. It means an object can return true for both `is_public` and `is_private`. We invite Griffe users to mostly rely on `is_public` and `not is_public`.
324
325 It is possible to force `is_public` and `is_deprecated` to return true or false by setting the [`public`][griffe.Object.public] and [`deprecated`][griffe.Object.deprecated] fields respectively. These fields are typically set by extensions that support new ways of marking objects as public or deprecated.
326
327 ## Imports/exports
328
329 Modules and classes populate their [`imports`][griffe.Object.imports] field with names that were imported from other modules. Similarly, modules populate their [`exports`][griffe.Object.exports] field with names that were exported by being listed into the module's `__all__` attribute. Each object then provides then [`is_imported`][griffe.Object.is_imported] and [`is_exported`][griffe.Object.is_exported] fields, which tell if an object was imported or exported respectively. Additionally, objects also provide an [`is_wildcard_exposed`][griffe.Object.is_wildcard_exposed] field that tells if an object is exposed to wildcard imports, i.e. will be imported when another module does `from this_module import *`.
330
331 ## Docstrings
332
333 Each object has an optional [`docstring`][griffe.Object.docstring] attached to it. To check whether it has one without comparing against `None`, the two following fields can be used:
334
335 - [`has_docstring`][griffe.Object.has_docstring]: whether this object has a docstring (even empty)
336 - [`has_docstrings`][griffe.Object.has_docstrings]: same thing, but recursive; whether this object or any of its members has a docstring (even empty)
337
338 [Docstrings][griffe.Docstring] provide their cleaned-up [`value`][griffe.Docstring.value] (de-indented string, stripped from leading and trailing newlines), as well as their starting and ending line numbers with [`lineno`][griffe.Docstring.lineno] and [`endlineno`][griffe.Docstring.endlineno].
339
340 Docstrings can be parsed against several [docstring-styles](../../reference/docstrings.md), which are micro-formats that allow documenting things such as parameters, returned values, raised exceptions, etc..
341
342 When loading a package, it is possible to specify the docstring style to attach to every docstring (see the `docstring_parser` parameter of [`griffe.load`][griffe.load]). Accessing the [`parsed`][griffe.Docstring.parsed] field of a docstring will use this style to parse the docstring and return a list of [docstring sections][advanced-api-sections]. Each section has a `value` whose shape depends on the section kind. For example, parameter sections have a list of parameter representations as value, while a text section only has a string as value.
343
344 After a package is loaded, it is still possible to change the style used for specific docstrings by either overriding their [`parser`][griffe.Docstring.parser] and [`parser_options`][griffe.Docstring.parser_options] attributes, or by calling their [`parse()`][griffe.Docstring.parse] method with a different style:
345
346 ```pycon
347 >>> import griffe
348 >>> markdown = griffe.load("markdown", docstring_parser="google")
349 >>> markdown["Markdown"].docstring.parse("numpy")
350 [...]
351 ```
352
353 Do note, however, that the `parsed` attribute is cached, and won't be reset when overriding the `parser` or `parser_options` values.
354
355 Docstrings have a [`parent`][griffe.Docstring.parent] field too, that is a reference to their respective module, class, function, attribute or type alias.
356
357 ## Model-specific fields
358
359 Models have most fields in common, but also have specific fields.
360
361 ### Modules
362
363 - [`imports_future_annotations`][griffe.Module.imports_future_annotations]: Whether the module imports [future annotations](https://peps.python.org/pep-0563/), which changes the way we parse type annotations.
364 - [`overloads`][griffe.Module.overloads]: A dictionary to store overloads for module-level functions.
365
366 ### Classes
367
368 - [`bases`][griffe.Class.bases]: A list of class bases in the form of [expressions][griffe.Expr].
369 - [`resolved_bases`][griffe.Class.resolved_bases]: A list of class bases, in the form of [Class][griffe.Class] objects. Only the bases that were loaded are returned, the others are discarded.
370 - [`mro()`][griffe.Class.mro]: A method to compute the Method Resolution Order in the form of a list of [Class][griffe.Class] objects.
371 - [`overloads`][griffe.Class.overloads]: A dictionary to store overloads for class-level methods.
372 - [`decorators`][griffe.Class.decorators]: The [decorators][griffe.Decorator] applied to the class.
373 - [`parameters`][griffe.Class.parameters]: The [parameters][griffe.Parameters] of the class' `__init__` method, if any.
374 - [`type_parameters`][griffe.Class.type_parameters]: The [type parameters][griffe.TypeParameters] of the class.
375
376 ### Functions
377
378 - [`decorators`][griffe.Function.decorators]: The [decorators][griffe.Decorator] applied to the function.
379 - [`overloads`][griffe.Function.overloads]: The overloaded signatures of the function.
380 - [`parameters`][griffe.Function.parameters]: The [parameters][griffe.Parameters] of the function.
381 - [`returns`][griffe.Function.returns]: The type annotation of the returned value, in the form of an [expression][griffe.Expr]. The `annotation` field can also be used, for compatibility with attributes.
382 - [`type_parameters`][griffe.Function.type_parameters]: The [type parameters][griffe.TypeParameters] of the function.
383
384 ### Attributes
385
386 - [`annotation`][griffe.Attribute.annotation]: The type annotation of the attribute, in the form of an [expression][griffe.Expr].
387 - [`value`][griffe.Attribute.value]: The value of the attribute, in the form of an [expression][griffe.Expr].
388 - [`deleter`][griffe.Attribute.deleter]: The property deleter.
389 - [`setter`][griffe.Attribute.setter]: The property setter.
390
391 ### Type aliases
392 - [`value`][griffe.TypeAlias.value]: The value of the type alias, in the form of an [expression][griffe.Expr].
393 - [`type_parameters`][griffe.TypeAlias.type_parameters]: The [type parameters][griffe.TypeParameters] of the type alias.
394
395 ### Alias
396
397 - [`alias_lineno`][griffe.Alias.alias_lineno]: The alias line number (where the object is imported).
398 - [`alias_endlineno`][griffe.Alias.alias_endlineno]: The alias ending line number (where the object is imported).
399 - [`target`][griffe.Alias.target]: The alias target (a module, class, function or attribute).
400 - [`target_path`][griffe.Alias.target_path]: The path of the alias target, as a string.
401 - [`wildcard`][griffe.Alias.wildcard]: Whether this alias represents a wildcard import, and if so from which module.
402 - [`resolve_target()`][griffe.Alias.resolve_target]: A method that resolves the target when called.
403
404 ## Expressions
405
406 When parsing source code, Griffe builds enhanced ASTs for type annotations, decorators, parameter defaults, attribute values, etc.
407
408 These "expressions" are very similar to what Python's [ast][] module gives you back when parsing source code, with a few differences: attributes like `a.b.c.` are flattened, and names like `a` have a parent object attached to them, a Griffe object, allowing to resolve this name to its full path given the scope of its parent.
409
410 You can write some code below and print annotations or attribute values with [Rich]'s pretty printer to see how expressions look like.
411
412 ```pyodide install="griffe,rich" theme="tomorrow,dracula"
413 from griffe import temporary_visited_module
414 from rich.pretty import pprint
415
416 code = """
417 from dataclasses import dataclass
418 from random import randint
419
420 @dataclass
421 class Bar:
422 baz: int
423
424 def get_some_baz() -> int:
425 return randint(0, 10)
426
427 foo: Bar = Bar(baz=get_some_baz())
428 """
429
430 with temporary_visited_module(code) as module:
431 pprint(module["foo"].annotation)
432 pprint(module["foo"].value)
433 ```
434
435 Ultimately, these expressions are what allow downstream tools such as [mkdocstrings' Python handler][mkdocstrings-python] to render cross-references to every object it knows of, coming from the current code base or loaded from object inventories (objects.inv files).
436
437 During static analysis, these expressions also allow analyzing decorators, dataclass fields, and many more things in great detail, and in a robust manner, to build third-party libraries support in the form of [Griffe extensions](extending.md).
438
439 To learn more about expressions, read their [API reference](../../reference/api/expressions.md).
440
441 ### Modernization
442
443 The Python language keeps evolving, and often library developers must continue supporting a few minor versions of Python. Therefore they cannot use some features that were introduced in the latest versions.
444
445 Yet this doesn't mean they can't enjoy latest features in their own docs: Griffe allows to "modernize" expressions, for example by replacing `typing.Union` with PEP 604 type unions `|`. Thanks to this, downstream tools like [mkdocstrings][mkdocstrings-python] can automatically transform type annotations into their modern equivalent. This improves consistency in your docs, and shows users how to use your code with the latest features of the language.
446
447 To modernize an expression, simply call its [`modernize()`][griffe.Expr.modernize] method. It returns a new, modernized expression. Some parts of the expression might be left unchanged, so be careful if you decide to mutate them.
448
449 Modernizations applied:
450
451 - `typing.Dict[A, B]` becomes `dict[A, B]`
452 - `typing.List[A]` becomes `list[A]`
453 - `typing.Set[A]` becomes `set[A]`
454 - `typing.Tuple[A]` becomes `tuple[A]`
455 - `typing.Union[A, B]` becomes `A | B`
456 - `typing.Optional[A]` becomes `A | None`
457
458 ## Next steps
459
460 In this chapter we saw many of the fields that compose our models, and how and why to use them. Now you might be interested in [extending](extending.md) or [serializing](serializing.md) the API data, or [checking for API breaking changes](checking.md).
461
462 [mkdocstrings-python]: https://mkdocstrings.github.io/python
463 [rich]: https://rich.readthedocs.io/en/stable/