| 1 | # `dataclasses` |
| 2 | |
| 3 | The `dataclasses` extension adds support for [dataclasses][] from the standard library. It works both statically and dynamically. When used statically, it re-creates the `__init__` methods and their signatures (as Griffe objects), that would otherwise be created at runtime. When used dynamically, it does nothing since `__init__` methods are created by the library and can be inspected normally. |
| 4 | |
| 5 | Example: |
| 6 | |
| 7 | ```python |
| 8 | from dataclasses import dataclass |
| 9 | |
| 10 | |
| 11 | @dataclass |
| 12 | class Room: |
| 13 | uid: int |
| 14 | name: str |
| 15 | capacity: int = 10 |
| 16 | available: bool = True |
| 17 | ``` |
| 18 | |
| 19 | With the `dataclasses` extension enabled, the Griffe object for the `Room` class will get an `__init__` method with the following signature: |
| 20 | |
| 21 | ```python |
| 22 | def __init__(self, uid: int, name: str, capacity: int = 10, available: bool = True) -> None: |
| 23 | ... |
| 24 | ``` |
| 25 | |
| 26 | Additional metadata like `ClassVar`, the `init` and `kw_only` parameters, or the `KW_ONLY` sentinel are also recognized and will update the `__init__` method signature accordingly. |
| 27 | |
| 28 | **This extension is enabled by default.** It is always added last. If you need to give it a higher priority, you can explictly enable it to change its position in the list of extensions (it will run only once): |
| 29 | |
| 30 | === "CLI" |
| 31 | ```console |
| 32 | $ griffe dump -e dataclasses,other my_package |
| 33 | ``` |
| 34 | |
| 35 | === "Python" |
| 36 | ```python |
| 37 | import griffe |
| 38 | |
| 39 | my_package = griffe.load("my_package", extensions=griffe.load_extensions("dataclasses", "other")) |
| 40 | ``` |
| 41 | |
| 42 | === "mkdocstrings" |
| 43 | ```yaml title="mkdocs.yml" |
| 44 | plugins: |
| 45 | - mkdocstrings: |
| 46 | handlers: |
| 47 | python: |
| 48 | options: |
| 49 | extensions: |
| 50 | - dataclasses |
| 51 | - other |
| 52 | ``` |
| 53 |