Debian Codegraph @

docs/extensions/built-in/unpack-typeddict.md

raw symbols SCIP
1 # `unpack_typeddict`
2
3 The `unpack_typeddict` extension adds support for [`Unpack`][typing.Unpack] and [`TypedDict`][typing.TypedDict] from the standard library. When enabled, it will add an `__init__` method to typed dictionaries, and expand `**kwargs: Unpack[...]` (the ellipsis being a [typed dict][typing.TypedDict] class) in function signatures to the relevant parameters, using the typed dict attributes or added signature. The extension will also update any Parameters section in the function docstring, to reflect the signature update.
4
5 Example:
6
7 ```python
8 from typing import TypedDict, Unpack
9
10
11 class GreetKwargs(TypedDict):
12 name: str
13 """The name of a person to greet."""
14 shout: bool
15 """Whether to shout."""
16
17
18 def greet(**kwargs: Unpack[GreetKwargs]) -> str:
19 """Greet someone.
20
21 Parameters:
22 **kwargs: Greet parameters.
23
24 Returns:
25 A message.
26 """
27 message = f"Hello {kwargs['name']}!"
28 if kwargs["shout"]:
29 return message.upper() + "!!"
30 return message
31 ```
32
33 With the `unpack_typeddict` extension enabled, the data loaded by Griffe will be updated as follows:
34
35 ```python
36 class GreetKwargs(TypedDict):
37 # Attributes removed from Griffe data.
38
39 # Added by the extension to Griffe data (not to the runtime class):
40 def __init__(self, *, name: str, shout: bool) -> None:
41 """
42 Parameters:
43 name: The name of a person to greet.
44 shout: Whether to shout.
45 """
46
47
48 def greet(*, name: str, shout: bool) -> str:
49 """Greet someone.
50
51 Parameters:
52 name: The name of a person to greet.
53 shout: Whether to shout.
54
55 Returns:
56 A message.
57 """
58 ```
59
60 Thanks to this `__init__` method now appearing in the typed dictionary, tools like mkdocstrings can now render a proper signature for `GreetKwargs`.
61
62 NOTE: Our example shows a Google-style docstring, but we actually insert a structured docstring section into the parsed data, which is style-agnostic, so it works with any docstring style.
63
64 To enable the extension:
65
66 === "CLI"
67 ```console
68 $ griffe dump -e unpack_typeddict my_package
69 ```
70
71 === "Python"
72 ```python
73 import griffe
74
75 my_package = griffe.load("my_package", extensions=griffe.load_extensions("unpack_typeddict"))
76 ```
77
78 === "mkdocstrings"
79 ```yaml title="mkdocs.yml"
80 plugins:
81 - mkdocstrings:
82 handlers:
83 python:
84 options:
85 extensions:
86 - unpack_typeddict
87 ```