• Stars
    star
    192
  • Rank 202,019 (Top 4 %)
  • Language
    Python
  • License
    Other
  • Created over 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python library to load dynamically typed data into statically typed data structures

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.

GPLv3 logo

Donate to LtWorf

Example

For example this dictionary, loaded from a json:

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

Can be treated more easily if loaded into this type:

@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:

t_data = typedload.load(data, Logins)

And then converted back:

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 (requires Python 3.8)
  • TypedDict (requires Python 3.8)
  • datetime.date, datetime.time, datetime.datetime
  • Path
  • IPv4Address, IPv6Address
  • typing.Any
  • typing.NewType

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.

# 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

Documentation

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.

More Repositories

1

localslackirc

IRC gateway for slack, running on localhost for one user
Python
107
star
2

relational

Educational tool for relational algebra
Python
86
star
3

weborf

Shares files using the HTTP protocol. Provides CLI and GUI. Allows using webdav.
C
54
star
4

funny-manpages

Funny unix manpages
Makefile
24
star
5

lapdog

Take actions when specific devices appear/disappear from your LAN
C++
17
star
6

vasttrafik-cli

Migrated to codeberg
Python
8
star
7

ultimateultimateguitar

CLI client to ultimate-guitar website
Python
8
star
8

python-acpi

Provides a python module to interface with ACPI things, and a script to listen to events and react to them by changing the frequency or locking the screen.
Python
5
star
9

ynew

Execute a script in a new yakuake tab
Shell
4
star
10

trabucco

Can launch your 90kg applications for 300m (It's a launcher, like katapult, but better).
C++
4
star
11

scurpiddu

Music player based on mpv and Qt
C++
4
star
12

DomainUserAgent

This extension changes the user agent depending on the hostname.
JavaScript
3
star
13

rtcsusp

Use the RTC to wake up at a given time
Python
2
star
14

InstagramPhotoLink

Browser extension to show the link to the images on instagram
JavaScript
2
star
15

ltdata

IRC bot in python
Python
2
star
16

rssagk

RSS aggregator for symbian
Python
1
star
17

cooja-dbus

Cooja plugin to control the simulation using dbus.
Java
1
star
18

leggero

Educational tool to improve music reading skills
C++
1
star
19

parolottero

Word game similar to Boggle and Ruzzle
C++
1
star
20

nitroxcalc

Nitrox calculations
QML
1
star
21

srtgen

Automatically generate .srt files from media files.
Python
1
star
22

canary

Tool to check for memory overflows
C
1
star
23

rais

Yet another privacy oriented browser
C++
1
star
24

anairc

Anairc is a simple distributed chat written in java, usable in LAN enviroments without any server.
Java
1
star
25

international_code_of_conduct

Code of conduct for international projects with international contributors. Still a draft.
1
star
26

DiveShare

Service to share divelogs online
Python
1
star