File: dataclasses.md

package info (click to toggle)
python-griffe 1.15.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,292 kB
  • sloc: python: 17,202; makefile: 47; sh: 24; javascript: 13
file content (53 lines) | stat: -rw-r--r-- 1,694 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# `dataclasses`

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.

Example:

```python
from dataclasses import dataclass


@dataclass
class Room:
    uid: int
    name: str
    capacity: int = 10
    available: bool = True
```

With the `dataclasses` extension enabled, the Griffe object for the `Room` class will get an `__init__` method with the following signature:

```python
def __init__(self, uid: int, name: str, capacity: int = 10, available: bool = True) -> None:
    ...
```

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.

**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):

=== "CLI"
    ```console
    $ griffe dump -e dataclasses,other my_package
    ```

=== "Python"
    ```python
    import griffe

    my_package = griffe.load("my_package", extensions=griffe.load_extensions("dataclasses", "other"))
    ```

=== "mkdocstrings"
    ```yaml title="mkdocs.yml"
    plugins:
    - mkdocstrings:
        handlers:
          python:
            options:
              extensions:
              - dataclasses
              - other
    ```