File: README.md

package info (click to toggle)
typedload 2.37-1
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 840 kB
  • sloc: python: 3,225; makefile: 146
file content (156 lines) | stat: -rw-r--r-- 3,981 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
typedload
=========

Load and dump json-like data into typed data structures in Python3, enforcing
a schema on the data.

This module provides an API to load dictionaries and lists (usually loaded
from json) into Python's NamedTuples, dataclass, sets, enums, and various
other typed data structures; respecting all the type-hints and performing
type checks or casts when needed.

It can also dump from typed data structures to json-like dictionaries and lists.

It is very useful for projects that use Mypy and deal with untyped data
like json, because it guarantees that the data will follow the specified schema.

It is released with a GPLv3 license but [it is possible to ask for LGPLv3](mailto:tiposchi@tiscali.it).

![GPLv3 logo](docs/gpl3logo.png)

[![Donate to LtWorf](docs/donate.svg)](https://liberapay.com/ltworf/donate)

Example
=======

For example this dictionary, loaded from a json:

```python
data = {
    'users': [
        {
            'username': 'salvo',
            'shell': 'bash',
            'sessions': ['pts/4', 'tty7', 'pts/6']
        },
        {
            'username': 'lop'
        }
    ],
}
```


Can be treated more easily if loaded into this type:

```python
@dataclasses.dataclass
class User:
    username: str
    shell: str = 'bash'
    sessions: List[str] = dataclasses.field(default_factory=list)

class Logins(NamedTuple):
    users: List[User]
```

And the data can be loaded into the structure with this:

```python
t_data = typedload.load(data, Logins)
```

And then converted back:

```python
data = typedload.dump(t_data)
```

Supported types
===============

Since this is not magic, not all types are supported.

The following things are supported:

 * Basic python types (int, str, bool, float, NoneType)
 * NamedTuple
 * Enum
 * Optional[SomeType]
 * List[SomeType]
 * Dict[TypeA, TypeB]
 * Tuple[TypeA, TypeB, TypeC] and Tuple[SomeType, ...]
 * Set[SomeType]
 * Union[TypeA, TypeB]
 * dataclass
 * attr.s
 * ForwardRef (Refer to the type in its own definition)
 * Literal
 * TypedDict
 * datetime.date, datetime.time, datetime.datetime
 * re.Pattern
 * Path
 * IPv4Address, IPv6Address
 * typing.Any
 * typing.NewType
 * uuid.UUID

Unions
------

typedload works fine with untagged unions. However using Literal fields to tag them makes it much faster.

Using Mypy
==========

Mypy and similar tools work without requiring any plugins.

```python
# This is treated as Any, no checks done.
data = json.load(f)

# This is treated as Dict[str, int]
# but there will be runtime errors if the data does not
# match the expected format
data = json.load(f)  # type: Dict[str, int]

# This is treated as Dict[str, int] and an exception is
# raised if the actual data is not Dict[str, int]
data = typedload.load(json.load(f), Dict[str, int])
```

So when using Mypy, it makes sense to make sure that the type is correct,
rather than hoping the data will respect the format.

Extending
=========

Type handlers can easily be added, and existing ones can be replaced, so the library is fully cusomizable and can work with any type.

Inheriting a base class is not required.

Install
=======

* `pip install typedload`
* `apt install python3-typedload`
* Latest and greatest .deb file is in [releases](https://codeberg.org/ltworf/typedload/releases)

Documentation
=============

* [Online documentation](https://ltworf.codeberg.page/typedload/)
* In the docs/ directory

The tests are hard to read but provide more in depth examples of
the capabilities of this module.

Used by
=======

As dependency, typedload is used by those entities. Feel free to add to the list.

* [Lyft](https://eng.lyft.com/python-upgrade-playbook-1479145d52f4)
* Several universities around the world (via [Relational](https://ltworf.codeberg.page/relational/))
* People who love IRC (via [localslackirc](https://github.com/ltworf/localslackirc))
* No clue but it gets thousands of downloads per day [according to pypi](https://pypistats.org/packages/typedload)