typedload/setup.py0000764000175000017500000000175114721335136013623 0ustar salvosalvo#!/usr/bin/python3 # This file is auto generated. Do not modify from setuptools import setup setup( name='typedload', version='2.37', description='Load and dump data from json-like format into typed data structures', readme='README.md', url='https://ltworf.codeberg.page/typedload/', author="Salvo 'LtWorf' Tomaselli", author_email='tiposchi@tiscali.it', license='GPL-3.0-only', classifiers=['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Typing :: Typed', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: 3.13'], keywords='typing types mypy json schema json-schema python3 namedtuple enums dataclass pydantic', packages=['typedload'], package_data={"typedload": ["py.typed", "__init__.pyi"]}, ) typedload/Makefile0000664000175000017500000001071314721335070013543 0ustar salvosalvoMINIMUM_PYTHON_VERSION=3.9 all: pypi .PHONY: test test: python3 -m tests .PHONY: mypy mypy: mypy --python-version=$(MINIMUM_PYTHON_VERSION) --config-file mypy.conf typedload mypy --python-version=$(MINIMUM_PYTHON_VERSION) example.py mypy --python-version=$(MINIMUM_PYTHON_VERSION) tests/mypy_*.py pyproject.toml: docs/CHANGELOG.md ./gensetup.py --$@ setup.py: docs/CHANGELOG.md README.md ./gensetup.py --$@ chmod u+x setup.py pypi: pyproject.toml setup.py typedload mkdir -p dist pypi ./setup.py sdist ./setup.py bdist_wheel mv dist/typedload-`head -1 CHANGELOG`.tar.gz pypi mv dist/*whl pypi rmdir dist gpg --detach-sign -a pypi/typedload-`head -1 CHANGELOG`.tar.gz gpg --detach-sign -a pypi/typedload-`head -1 CHANGELOG`-py3-none-any.whl # Debian needs setup and pyproject to be kept since they are in the # dist file. However I want to clean them or they will become outdated # and not regenerated .PHONY: debian_clean debian_clean: $(RM) -r pypi $(RM) -r build $(RM) -r .mypy_cache $(RM) -r typedload.egg-info/ $(RM) -r .pybuild $(RM) MANIFEST $(RM) -r `find . -name __pycache__` $(RM) typedload_`head -1 CHANGELOG`.orig.tar.gz $(RM) typedload_`head -1 CHANGELOG`.orig.tar.gz.asc $(RM) -r deb-pkg $(RM) -r html $(RM) -r perftest.output $(RM) docs/*_docgen.md .PHONY: clean clean: debian_clean $(RM) setup.py $(RM) pyproject.toml .PHONY: dist dist: clean setup.py pyproject.toml cd ..; tar -czvvf typedload.tar.gz \ typedload/setup.py \ typedload/Makefile \ typedload/tests \ typedload/docs \ typedload/docgen \ typedload/mkdocs.yml \ typedload/LICENSE \ typedload/CONTRIBUTING.md \ typedload/CHANGELOG \ typedload/README.md \ typedload/example.py \ typedload/mypy.conf \ typedload/pyproject.toml \ typedload/typedload mv ../typedload.tar.gz typedload_`./setup.py --version`.orig.tar.gz gpg --detach-sign -a *.orig.tar.gz .PHONY: upload upload: pypi twine upload --username __token__ --password `cat .token` pypi/* deb-pkg: dist mv typedload_`./setup.py --version`.orig.tar.gz* /tmp cd /tmp; tar -xf typedload_*.orig.tar.gz cp -r debian /tmp/typedload/ cd /tmp/typedload/; dpkg-buildpackage --changes-option=-S mkdir deb-pkg mv /tmp/typedload_* /tmp/python3-typedload*.deb deb-pkg $(RM) -r /tmp/typedload lintian --pedantic -E --color auto -i -I deb-pkg/*.changes deb-pkg/*.deb docs/typedload_docgen.md: typedload/__init__.py ./docgen $@ docs/typedload.dataloader_docgen.md: typedload/dataloader.py ./docgen $@ docs/typedload.datadumper_docgen.md: typedload/datadumper.py ./docgen $@ docs/typedload.exceptions_docgen.md: typedload/exceptions.py ./docgen $@ docs/typedload.typechecks_docgen.md: typedload/typechecks.py ./docgen $@ html: \ docs/*.svg \ docs/CHANGELOG.md \ docs/CODE_OF_CONDUCT.md \ docs/comparisons.md \ docs/CONTRIBUTING.md \ docs/deferred_evaluation.md \ docs/docs \ docs/docs/gpl3logo.png \ docs/errors.md \ docs/examples.md \ docs/gpl3logo.png \ docs/origin_story.md \ docs/performance.md \ docs/README.md \ docs/SECURITY.md \ docs/supported_types.md \ docs/typedload.datadumper_docgen.md \ docs/typedload.dataloader_docgen.md \ docs/typedload_docgen.md \ docs/typedload.exceptions_docgen.md \ docs/typedload.typechecks_docgen.md \ mkdocs.yml mkdocs build # Download cloudflare crap mkdir -p html/cdn cd html/cdn; wget --continue `cat ../*html | grep cloudflare | grep min.css | sort | uniq | cut -d\" -f4` cd html/cdn; wget --continue `cat ../*html | grep cloudflare | grep min.js | sort | uniq | cut -d\" -f2` # Fix html pages for page in html/*.html; do \ sed -i 's,https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/styles/github.min.css,cdn/github.min.css,g' $${page}; \ sed -i 's,https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.8.0/highlight.min.js,cdn/highlight.min.js,g' $${page}; \ echo "" >> $${page}; \ done if (cat html/*.html | grep cdnjs.cloudflare.com); then echo trackers found; false; fi .PHONY: publish_html publish_html: html git checkout pages rm -rf cdn css docs fonts img js search mv html/* . git add cdn css docs fonts img js search git add `git status --porcelain | grep '^ M' | cut -d\ -f3` git commit -m "Deployed manually to workaround MkDocs" git push git checkout - perftest.output/perf.p: @echo export MOREVERSIONS=1 to compare more versions perftest/performance.py .PHONY: gnuplot gnuplot: perftest.output/perf.p cd "perftest.output"; gnuplot -persist -c perf.p typedload/tests/0000775000175000017500000000000014721335070013243 5ustar salvosalvotypedload/tests/test_literal.py0000664000175000017500000001125314721335070016312 0ustar salvosalvo# typedload # Copyright (C) 2019-2022 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from dataclasses import dataclass from typing import Literal, NamedTuple, TypedDict, Union import unittest from typedload import dataloader, load, dump, typechecks class TestLiteralLoad(unittest.TestCase): def test_literalvalues(self): assert isinstance(typechecks.literalvalues(Literal[1]), set) assert typechecks.literalvalues(Literal[1]) == {1} assert typechecks.literalvalues(Literal[1, 1]) == {1} assert typechecks.literalvalues(Literal[1, 2]) == {1, 2} def test_load(self): l = Literal[1, 2, 'a'] assert load(1, l) == 1 assert load(2, l) == 2 assert load('a', l) == 'a' def test_fail(self): l = Literal[1, 2, 'a'] with self.assertRaises(ValueError): load(3, l) def test_discriminatorliterals_wrong(self): assert typechecks.discriminatorliterals(int) == {} def test_discriminatorliterals_namedtuple(self): class A(NamedTuple): t: Literal['a', 'b'] i: int q: str class B(NamedTuple): t: Literal[33] q: Literal[12] i: int class C(NamedTuple): t: Literal['a'] i: int assert typechecks.discriminatorliterals(A) == {'t': {'a', 'b'}} assert typechecks.discriminatorliterals(B) == {'t': {33,}, 'q': {12,}} assert typechecks.discriminatorliterals(C) == {'t': {'a', }} def test_discriminatorliterals_typeddict(self): class A(TypedDict): t: Literal['a', 'b'] i: int q: str class B(TypedDict): t: Literal[33] q: Literal[12] i: int class C(TypedDict): t: Literal['a'] i: int assert typechecks.discriminatorliterals(A) == {'t': {'a', 'b'}} assert typechecks.discriminatorliterals(B) == {'t': {33,}, 'q': {12,}} assert typechecks.discriminatorliterals(C) == {'t': {'a', }} def test_discriminatorliterals_dataclass(self): @dataclass class A: t: Literal['a', 'b'] i: int q: str @dataclass class B: t: Literal[33] q: Literal[12] i: int @dataclass class C: t: Literal['a'] i: int assert typechecks.discriminatorliterals(A) == {'t': {'a', 'b'}} assert typechecks.discriminatorliterals(B) == {'t': {33,}, 'q': {12,}} assert typechecks.discriminatorliterals(C) == {'t': {'a', }} def test_discriminatorliterals_attr(self): try: from attr import attrs, attrib except ImportError: return @attrs class A: t: Literal['a', 'b'] = attrib() i: int = attrib() q: str = attrib() @attrs class B: t: Literal[33] = attrib() q: Literal[12] = attrib() i: int = attrib() @attrs class C: t: Literal['a'] = attrib() i: int = attrib() assert typechecks.discriminatorliterals(A) == {'t': {'a', 'b'}} assert typechecks.discriminatorliterals(B) == {'t': {33,}, 'q': {12,}} assert typechecks.discriminatorliterals(C) == {'t': {'a', }} def test_literal_sorting(self): class A(NamedTuple): t: Literal[1] i: int class B(NamedTuple): t: Literal[2, 3] i: int assert load({'t': 1, 'i': 12}, Union[A, B]) == A(1, 12) assert load({'t': 2, 'i': 12}, Union[A, B]) == B(2, 12) assert load({'t': 3, 'i': 12}, Union[A, B]) == B(3, 12) def test_multiple_literal_sorting(self): class A(NamedTuple): t: Literal[1] u: Literal[1] class B(NamedTuple): t: Literal[2] i: int assert load({'t': 1, 'u': 1}, Union[A, B]) == A(1, 1) assert load({'t': 2, 'i': 12}, Union[A, B]) == B(2, 12) typedload/tests/test_dumpload.py0000664000175000017500000000272114721335070016463 0ustar salvosalvo# typedload # Copyright (C) 2018 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from enum import Enum from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union import unittest from typedload import dump, load class Result(Enum): PASS = True FAIL = False class Student(NamedTuple): name: str id: int email: Optional[str] = None class ExamResults(NamedTuple): results: List[Tuple[Student, Result]] class TestDumpLoad(unittest.TestCase): def test_dump_load_results(self): results = ExamResults( [ (Student('Anna', 1), Result.PASS), (Student('Alfio', 2), Result.PASS), (Student('Iano', 3, 'iano@iano.it'), Result.PASS), ] ) assert load(dump(results), ExamResults) == results typedload/tests/test_typealias.py0000664000175000017500000001076614721335070016661 0ustar salvosalvo# typedload # Copyright (C) 2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import unittest from dataclasses import dataclass from typing import List, Set, FrozenSet, Tuple, TypedDict, Required, NamedTuple # Run tests for attr only if it is installed try: from attr import define attr_module = True except ImportError: attr_module = False from typedload import typechecks, load class TestSimpleAliasLoad(unittest.TestCase): def test_basicload(self): type s = str type i = int assert load(3, i) == 3 assert load("iaffieddu", s) == "iaffieddu" def test_unionload(self): type IntOrStr = int | str assert load(3, IntOrStr) == 3 assert load("iaffieddu", IntOrStr) == "iaffieddu" assert load("3", IntOrStr) == "3" def test_forward_def_load(self): type t = int | A @dataclass class A: i: int assert load(3, t) == 3 assert load({'i': 3}, t) == A(3) def test_tuple(self): type Point = tuple[float, float] assert load([4,2], Point) == (4, 2) def test_tupleunion(self): type FPoint = tuple[float, float] type IPoint = tuple[int, int] type Point = FPoint | IPoint assert load([4,2], Point) == (4, 2) assert load([4.0,2.0], Point) == (4.0, 2.0) def test_nested(self): type i = int type IntOrStr = i | str r=load(3, IntOrStr) assert load(3, IntOrStr) == 3 type l = list[i] type L = List[i] assert load([1], l) == [1] assert load([1], L) == [1] type s = set[i] type S = Set[i] assert load([1], s) == {1} assert load([1], S) == {1} type f = frozenset[i] type F = FrozenSet[i] assert load([1], f) == frozenset({1}) assert load([1], F) == frozenset({1}) type t = tuple[i, ...] type T = Tuple[i, ...] assert load([1, 2], t) == (1, 2) assert load([1, 2], T) == (1, 2) class TestFieldAliasLoad(unittest.TestCase): def test_indataclass(self): type int_alias = int @dataclass class A: i: int_alias assert load({'i': 1}, A) == A(1) def test_intypeddict(self): type int_alias = int class A(TypedDict): i: Required[int_alias] assert load({'i': 1}, A) == {'i': 1} def test_innamedtuple(self): type int_alias = int class A(NamedTuple): i: int_alias assert load({'i': 1}, A) == A(1) if attr_module: def test_inattr(self): type int_alias = int @define class A: i: int_alias assert load({'i': 1}, A) == A(1) def test_unioninnamedtuple(self): type number = int | float class A(NamedTuple): i: number assert load({'i': 3}, A) == A(3) def test_listinnamedtuple(self): type number = int | float class A(NamedTuple): i: list[number] assert load({'i': [3]}, A) == A([3]) assert load({'i': [3.0]}, A) == A([3.0]) def test_listaliasinnamedtuple(self): type number = int | float type list_of_numbers = list[number] class A(NamedTuple): i: list_of_numbers assert load({'i': [3,4,5,0.1]}, A) == A([3,4,5,0.1]) def test_listunionaliasinnamedtuple(self): type list_of_numbers = list[int | float] class A(NamedTuple): i: list_of_numbers assert load({'i': [3,4,5,0.1]}, A) == A([3,4,5,0.1]) def test_nesteduniontuple(self): type FPoint = tuple[float, float] type IPoint = tuple[int, int] type Point = FPoint | IPoint class A(NamedTuple): i: list[Point] assert load({'i': [[1,1], [1.0, 1.0]]}, A) == A([(1,1), (1.0,1.0)]) typedload/tests/test_typeddict.py0000664000175000017500000001346214721335070016653 0ustar salvosalvo# typedload # Copyright (C) 2019-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from typing import TypedDict import unittest import sys from typedload import dataloader, load, dump, typechecks class Person(TypedDict): name: str age: float class A(TypedDict): val: str class B(TypedDict, total=False): val: str class C(A, total=False): vel: int class TestTypeddictLoad(unittest.TestCase): def test_mixed_totality(self): with self.assertRaises(TypeError): load({}, C) assert load({'val': 'a'}, C) == {'val': 'a'} with self.assertRaises(ValueError): load({'val': 'a', 'vel': 'q'}, C) assert load({'val': 'a', 'vel': 1}, C) == {'val': 'a', 'vel': 1} assert load({'val': 'a', 'vel': '1'}, C) == {'val': 'a', 'vel': 1} assert load({'val': 'a','vil': 2}, C) == {'val': 'a'} with self.assertRaises(TypeError): load({'val': 'a','vil': 2}, C, failonextra=True) def test_totality(self): with self.assertRaises(TypeError): load({}, A) assert load({}, B) == {} assert load({'val': 'a'}, B) == {'val': 'a'} assert load({'vel': 'q'}, B) == {} with self.assertRaises(TypeError): load({'vel': 'q'}, B, failonextra=True) def test_loadperson(self): o = {'name': 'pino', 'age': 1.1} assert load(o, Person) == o assert load({'val': 3}, A) == {'val': '3'} assert load({'val': 3, 'vil': 4}, A) == {'val': '3'} with self.assertRaises(TypeError): o.pop('age') load(o, Person) with self.assertRaises(TypeError): load({'val': 3, 'vil': 4}, A, failonextra=True) def test_is_typeddict(self): assert typechecks.is_typeddict(A) assert typechecks.is_typeddict(Person) assert typechecks.is_typeddict(B) if sys.version_info.minor >= 11: # NotRequired is present from 3.11 from typing import NotRequired, Required class TestRequired(unittest.TestCase): def test_normal(self): class A(TypedDict, total=False): a: int b: Required[int] assert load({'a': 1, 'b': 1}, A) == {'a': 1, 'b': 1} assert load({'b': 1}, A) == {'b': 1} with self.assertRaises(TypeError): load({}, A) def test_abnormal(self): class A(TypedDict, total=True): a: int b: Required[int] assert load({'a': 1, 'b': 1}, A) == {'a': 1, 'b': 1} with self.assertRaises(TypeError): load({}, A) with self.assertRaises(TypeError): load({'a': 1}, A) with self.assertRaises(TypeError): load({'b': 1}, A) def test_many(self): class A(TypedDict, total=True): a: Required[int] b: Required[int] c: NotRequired[int] d: NotRequired[int] class B(TypedDict, total=False): a: Required[int] b: Required[int] c: NotRequired[int] d: NotRequired[int] with self.assertRaises(TypeError): load({}, A) with self.assertRaises(TypeError): load({}, B) with self.assertRaises(TypeError): load({'c': 1}, A) with self.assertRaises(TypeError): load({'c': 1}, B) assert load({'a': 1, 'b': 1}, A) == {'a': 1, 'b': 1} assert load({'a': 1, 'b': 1}, B) == {'a': 1, 'b': 1} with self.assertRaises(ValueError): load({'a': 1, 'b': 'qqq'}, A) class TestNotRequired(unittest.TestCase): def test_standard(self): class A(TypedDict): i: int o: NotRequired[int] assert load({'i': 1}, A) == {'i': 1} assert load({'i': 1, 'o': 2}, A) == {'i': 1, 'o': 2} def test_nontotal(self): class A(TypedDict, total = False): i: int o: NotRequired[int] assert load({}, A) == {} assert load({'i': 1}, A) == {'i': 1} assert load({'i': 1, 'o': 2}, A) == {'i': 1, 'o': 2} def test_mixtotal(self): class A(TypedDict): a: int b: NotRequired[int] class B(A, total=False): c: int d: NotRequired[int] with self.assertRaises(TypeError): load({}, B) assert load({'a': 1}, B) == {'a': 1} assert load({'a': 1, 'd':12}, B) == {'a': 1, 'd': 12} if sys.version_info.minor >= 13: from typing import ReadOnly class TestReadOnly(unittest.TestCase): def test_load(self): class A(TypedDict): i: ReadOnly[int] q=load({'i': 1}, A) assert load({'i': 1}, A) == {'i': 1} def test_loadwithannotationnesting(self): class A(TypedDict, total=True): i: ReadOnly[NotRequired[int]] assert load({}, A) == {} assert load({'i': 1}, A) == {'i': 1} typedload/tests/test_orunion.py0000664000175000017500000000314314721335070016346 0ustar salvosalvo# typedload # Copyright (C) 2022 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import unittest from typedload import dataloader, load, dump, typechecks class TestOrUnion(unittest.TestCase): ''' From Python3.10 unions can be written as A | B. That is a completely different internal than Union[A, B] ''' def test_typechecker(self): assert typechecks.is_union(int | str) assert not typechecks.is_union(2 | 1) def test_uniontypes(self): u = int | str | float assert int in typechecks.uniontypes(u) assert str in typechecks.uniontypes(u) assert float in typechecks.uniontypes(u) assert bytes not in typechecks.uniontypes(u) assert bool not in typechecks.uniontypes(u) def test_loadnewunion(self): t = list[int] | str assert load('ciao', t) == 'ciao' assert load(['1', 1.0, 0], t) == [1, 1, 0] assert load(('1', 1.0, 0), t) == [1, 1, 0] typedload/tests/test_datadumper.py0000664000175000017500000001230114721335070016777 0ustar salvosalvo# typedload # Copyright (C) 2018-2023 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from enum import Enum from ipaddress import IPv4Address, IPv4Network, IPv4Interface, IPv6Address, IPv6Network, IPv6Interface from pathlib import Path import re from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union import unittest from uuid import UUID from typedload import datadumper, dump, load class EnumA(Enum): A: int = 1 B: str = '2' C: Tuple[int, int] = (1, 2) class NamedA(NamedTuple): a: int b: str c: str = 'no' class TestDumpLoad(unittest.TestCase): def test_enum(self): assert load(dump(EnumA.C), EnumA) == EnumA.C class TestLegacyDump(unittest.TestCase): def test_dump(self): A = NamedTuple('A',[('a', int), ('b', str)]) assert dump(A(1, '12')) == {'a': 1, 'b': '12'} class TestStrconstructed(unittest.TestCase): def test_dump_strconstructed(self): dumper = datadumper.Dumper() class Q: def __str__(self): return '42' dumper.strconstructed.add(Q) assert dumper.dump(Q()) == '42' class TestBasicDump(unittest.TestCase): def test_dump_namedtuple(self): dumper = datadumper.Dumper() assert dumper.dump(NamedA(1, 'a')) == {'a': 1, 'b': 'a'} assert dumper.dump(NamedA(1, 'a', 'yes')) == {'a': 1, 'b': 'a', 'c': 'yes'} dumper.hidedefault = False assert dumper.dump(NamedA(1, 'a')) == {'a': 1, 'b': 'a', 'c': 'no'} def test_dump_dict(self): dumper = datadumper.Dumper() assert dumper.dump({EnumA.B: 'ciao'}) == {'2': 'ciao'} def test_dump_set(self): dumper = datadumper.Dumper() assert dumper.dump(set(range(3))) == [0, 1, 2] assert dumper.dump(frozenset(range(3))) == [0, 1, 2] def test_dump_enums(self): dumper = datadumper.Dumper() assert dumper.dump(EnumA.A) == 1 assert dumper.dump(EnumA.B) == '2' assert dumper.dump(EnumA.C) == [1, 2] def test_dump_iterables(self): dumper = datadumper.Dumper() assert dumper.dump([1]) == [1] assert dumper.dump((1, 2)) == [1, 2] assert dumper.dump([(1, 1), (0, 0)]) == [[1, 1], [0, 0]] assert dumper.dump({1, 2}) == [1, 2] def test_basic_types(self): # Casting enabled, by default dumper = datadumper.Dumper() assert dumper.dump(1) == 1 assert dumper.dump('1') == '1' assert dumper.dump(None) == None dumper.basictypes = {int, str} assert dumper.dump('1') == '1' assert dumper.dump(1) == 1 with self.assertRaises(ValueError): assert dumper.dump(None) == None assert dumper.dump(True) == True class TestHandlersDumper(unittest.TestCase): def test_custom_handler(self): class Q: def __eq__(self, other): return isinstance(other, Q) dumper = datadumper.Dumper() dumper.handlers.append(( lambda v: isinstance(v, Q), lambda l, v: 12 )) assert dumper.dump(Q()) == 12 def test_broken_handler(self): dumper = datadumper.Dumper() dumper.handlers.insert(0, (lambda v: 'a' + v is None, lambda l, v: None)) with self.assertRaises(TypeError): dumper.dump(1) dumper.raiseconditionerrors = False assert dumper.dump(1) == 1 def test_replace_handler(self): dumper = datadumper.Dumper() index = dumper.index([]) dumper.handlers[index] = (dumper.handlers[index][0], lambda *args: 3) assert dumper.dump([11]) == 3 class TestDumper(unittest.TestCase): def test_kwargs(self): with self.assertRaises(ValueError): dump(1, handlers=[]) class TestDumpCommonTypes(unittest.TestCase): def test_path(self): assert dump(Path('/')) == '/' def test_ipaddress(self): assert dump(IPv4Address('10.10.10.1')) == '10.10.10.1' assert dump(IPv4Network('10.10.10.0/24')) == '10.10.10.0/24' assert dump(IPv4Interface('10.10.10.1/24')) == '10.10.10.1/24' assert dump(IPv6Address('fe80::123')) == 'fe80::123' assert dump(IPv6Network('fe80::/64')) == 'fe80::/64' assert dump(IPv6Interface('fe80::123/64')) == 'fe80::123/64' def test_uuid(self): assert dump(UUID('631b09cb-016e-11ef-97ce-000000000001')) == '631b09cb-016e-11ef-97ce-000000000001' def test_pattern(self): assert dump(re.compile(r'[bc](at|ot)\d+')) == r'[bc](at|ot)\d+' assert dump(re.compile(br'[bc](at|ot)\d+')) == br'[bc](at|ot)\d+' typedload/tests/test_datetime.py0000664000175000017500000001025614721335070016454 0ustar salvosalvo# typedload # Copyright (C) 2023 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import datetime import unittest from typedload import load, dump, dataloader, datadumper class TestDatetimedump(unittest.TestCase): def test_isodatetime(self): dumper = datadumper.Dumper(isodates=True) assert dumper.dump(datetime.date(2011, 12, 12)) == '2011-12-12' assert dumper.dump(datetime.time(15, 41)) == '15:41:00' assert dumper.dump(datetime.datetime(2019, 5, 31, 12, 44, 22)) == '2019-05-31T12:44:22' assert dumper.dump(datetime.datetime(2023, 3, 20, 7, 43, 19, 906439, tzinfo=datetime.timezone.utc)) == '2023-03-20T07:43:19.906439+00:00' def test_datetime(self): dumper = datadumper.Dumper() assert dumper.dump(datetime.date(2011, 12, 12)) == [2011, 12, 12] assert dumper.dump(datetime.time(15, 41)) == [15, 41, 0, 0] assert dumper.dump(datetime.datetime(2019, 5, 31, 12, 44, 22)) == [2019, 5, 31, 12, 44, 22, 0] class TestDatetimeLoad(unittest.TestCase): def test_isoload(self): now = datetime.datetime.now() assert load(now.isoformat(), datetime.datetime) == now withtz = datetime.datetime(2023, 3, 20, 7, 43, 19, 906439, tzinfo=datetime.timezone.utc) assert load(withtz.isoformat(), datetime.datetime) == withtz date = datetime.date(2023, 4, 1) assert load(date.isoformat(), datetime.date) == date time = datetime.time(23, 44, 12) assert load(time.isoformat(), datetime.time) == time def test_date(self): loader = dataloader.Loader() assert loader.load((2011, 1, 1), datetime.date) == datetime.date(2011, 1, 1) assert loader.load((15, 33), datetime.time) == datetime.time(15, 33) assert loader.load((15, 33, 0), datetime.time) == datetime.time(15, 33) assert loader.load((2011, 1, 1), datetime.datetime) == datetime.datetime(2011, 1, 1) assert loader.load((2011, 1, 1, 22), datetime.datetime) == datetime.datetime(2011, 1, 1, 22) # Same but with lists assert loader.load([2011, 1, 1], datetime.date) == datetime.date(2011, 1, 1) assert loader.load([15, 33], datetime.time) == datetime.time(15, 33) assert loader.load([15, 33, 0], datetime.time) == datetime.time(15, 33) assert loader.load([2011, 1, 1], datetime.datetime) == datetime.datetime(2011, 1, 1) assert loader.load([2011, 1, 1, 22], datetime.datetime) == datetime.datetime(2011, 1, 1, 22) def test_exception(self): loader = dataloader.Loader() with self.assertRaises(TypeError): loader.load((2011, ), datetime.datetime) loader.load(33, datetime.datetime) class TestTimedelta(unittest.TestCase): def test_findhandlers(self): l = dataloader.Loader() d = datadumper.Dumper() l.index(datetime.timedelta) d.index(datetime.timedelta(1)) def test_dumpdelta(self): assert dump(datetime.timedelta(0, 1)) == 1.0 assert dump(datetime.timedelta(1, 1)) == 86400 + 1 assert dump(datetime.timedelta(3, 0.1)) == 86400 * 3 + 0.1 def test_loaddelta(self): assert load(1.0, datetime.timedelta) == datetime.timedelta(0, 1) assert load(86400, datetime.timedelta) == datetime.timedelta(1, 0) assert load(86400.0, datetime.timedelta) == datetime.timedelta(1, 0) def test_loaddump(self): for i in [(0, 1), (2,12), (9, 50), (600, 0.4), (1000, 501)]: delta = datetime.timedelta(*i) assert load(dump(delta), datetime.timedelta) == delta typedload/tests/test_exceptions.py0000664000175000017500000001251214721335070017036 0ustar salvosalvo# typedload # Copyright (C) 2021-2023 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import enum from typing import List, NamedTuple, Optional, Tuple, Set, FrozenSet import unittest from typedload import dataloader, load, dump, typechecks, exceptions class Firewall(NamedTuple): open_ports: List[int] class Networking(NamedTuple): nic: Optional[str] firewall: Firewall class Remote(NamedTuple): networking: Networking class Config(NamedTuple): remote: Optional[Remote] class Enumeration(enum.Enum): A = 1 B = '2' C = 3.0 class TestExceptionsStr(unittest.TestCase): def test_tuple_exceptions(self): try: load(('1',), Tuple[int, ...], basiccast=False) except exceptions.TypedloadException as e: assert e._path(e.trace) == '.[0]' try: load((1, '1',), Tuple[int, ...], basiccast=False) except exceptions.TypedloadException as e: assert e._path(e.trace) == '.[1]' try: load(('1'), Tuple[int], basiccast=False) except exceptions.TypedloadException as e: assert e._path(e.trace) == '.[0]' try: load(('1', 1), Tuple[int, int], basiccast=False) except exceptions.TypedloadException as e: assert e._path(e.trace) == '.[0]' try: load((1, '1'), Tuple[int, int], basiccast=False) except exceptions.TypedloadException as e: assert e._path(e.trace) == '.[1]' try: load((1,), Tuple[int, int], basiccast=False) except exceptions.TypedloadException as e: assert e._path(e.trace) == '.' def test_exceptions_str(self): incorrect = [ {'remote': {'networking': {'nic': "eth0", "firewall": {"open_ports":[1,2,3, 'a']}}}}, {'remote': {'networking': {'nic': "eth0", "firewall": {"closed_ports": [], "open_ports":[1,2,3]}}}}, {'remote': {'networking': {'noc': "eth0", "firewall": {"open_ports":[2,3]}}}}, {'romote': {'networking': {'nic': "eth0", "firewall": {"open_ports":[2,3]}}}}, {'remote': {'nitworking': {'nic': "eth0", "firewall": {"open_ports":[2,3]}}}}, ] paths = [] for i in incorrect: try: load(i, Config, basiccast=False, failonextra=True) assert False except exceptions.TypedloadException as e: for i in e.exceptions: paths.append(e._path(e.trace) + '.' + i._path(i.trace[1:])) #1st object assert paths[0] == '.remote.networking.firewall.open_ports.[3]' assert paths[1] == '.remote.' #2nd object assert paths[2] == '.remote.networking.firewall' assert paths[3] == '.remote.' #3rd object assert paths[4] == '.remote.networking' assert paths[5] == '.remote.' #4th object # Nothing because of no sub-exceptions, fails before the union #5th object assert paths[6] == '.remote.' assert paths[7] == '.remote.' assert len(paths) == 8 def test_tuple_exceptions_str(self): incorrect = [ [1, 1], [1, 1, 1], [1], [1, 1.2], [1, None], [1, None, 1], ] for i in incorrect: try: load(i, Tuple[int, int], basiccast=False, failonextra=True) except Exception as e: str(e) def test_enum_exceptions_str(self): incorrect = [ [1, 1], '3', 12, ] for i in incorrect: try: load(i, Enumeration, basiccast=False, failonextra=True) except Exception as e: str(e) def test_nested_wrong_type(self): with self.assertRaises(exceptions.TypedloadException): load([[1]], List[List[bytes]]) with self.assertRaises(exceptions.TypedloadException): load([[1]], List[Tuple[bytes, ...]]) with self.assertRaises(exceptions.TypedloadException): load([[1]], List[Set[bytes]]) with self.assertRaises(exceptions.TypedloadException): load([[1]], List[FrozenSet[bytes]]) def test_notiterable_exception(self): loader = dataloader.Loader() with self.assertRaises(exceptions.TypedloadTypeError): loader.load(None, List[int]) with self.assertRaises(exceptions.TypedloadTypeError): loader.load(None, Tuple[int, ...]) with self.assertRaises(exceptions.TypedloadTypeError): loader.load(None, Set[int]) with self.assertRaises(exceptions.TypedloadTypeError): loader.load(None, FrozenSet[int]) typedload/tests/test_dataloader.py0000664000175000017500000005054314721335070016763 0ustar salvosalvo# typedload # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import argparse from enum import Enum from ipaddress import IPv4Address, IPv6Address, IPv6Network, IPv4Network, IPv4Interface, IPv6Interface from pathlib import Path import re import sys import typing from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union, Any, NewType, FrozenSet import unittest from uuid import UUID from typedload import dataloader, load, exceptions class TestRealCase(unittest.TestCase): def test_stopboard(self): class VehicleType(Enum): ST = 'ST' TRAM = 'TRAM' BUS = 'BUS' WALK = 'WALK' BOAT = 'BOAT' class BoardItem(NamedTuple): name: str type: VehicleType date: str time: str stop: str stopid: str journeyid: str sname: Optional[str] = None track: str = '' rtDate: Optional[str] = None rtTime: Optional[str] = None direction: Optional[str] = None accessibility: str = '' bgColor: str = '#0000ff' fgColor: str = '#ffffff' stroke: Optional[str] = None night: bool = False c = { 'JourneyDetailRef': {'ref': 'https://api.vasttrafik.se/bin/rest.exe/v2/journeyDetail?ref=859464%2F301885%2F523070%2F24954%2F80%3Fdate%3D2018-04-08%26station_evaId%3D5862002%26station_type%3Ddep%26format%3Djson%26'}, 'accessibility': 'wheelChair', 'bgColor': '#00394d', 'date': '2018-04-08', 'direction': 'Kortedala', 'fgColor': '#fa8719', 'journeyid': '9015014500604285', 'name': 'Spårvagn 6', 'rtDate': '2018-04-08', 'rtTime': '12:27', 'sname': '6', 'stop': 'SKF, Göteborg', 'stopid': '9022014005862002', 'stroke': 'Solid', 'time': '12:17', 'track': 'B', 'type': 'TRAM' } loader = dataloader.Loader() loader.load(c, BoardItem) class TestStrconstructed(unittest.TestCase): def test_load_strconstructed(self): loader = dataloader.Loader() class Q: def __init__(self, p): self.param = p loader.strconstructed.add(Q) data = loader.load('42', Q) assert data.param == '42' class TestUnion(unittest.TestCase): def test_json(self): ''' This test would normally be flaky, but with the scoring of types in union, it should always work. ''' Json = Union[int, float, str, bool, None, List['Json'], Dict[str, 'Json']] data = [{},[]] loader = dataloader.Loader() loader.basiccast = False loader.frefs = {'Json' : Json} assert loader.load(data, Json) == data def test_str_obj(self): ''' Possibly flaky test. Testing automatic type sorting in Union It depends on python internal magic of sorting the union types ''' loader = dataloader.Loader() class Q(NamedTuple): a: int expected = Q(12) for _ in range(5000): t = eval('Union[str, Q]') assert loader.load({'a': 12}, t) == expected def test_ComplicatedUnion(self): class A(NamedTuple): a: int class B(NamedTuple): a: str class C(NamedTuple): val: Union[A, B] loader = dataloader.Loader() loader.basiccast = False assert type(loader.load({'val': {'a': 1}}, C).val) == A assert type(loader.load({'val': {'a': '1'}}, C).val) == B def test_optional(self): loader = dataloader.Loader() assert loader.load(1, Optional[int]) == 1 assert loader.load(None, Optional[int]) == None assert loader.load('1', Optional[int]) == 1 with self.assertRaises(ValueError): loader.load('ciao', Optional[int]) loader.basiccast = False loader.load('1', Optional[int]) def test_union(self): loader = dataloader.Loader() loader.basiccast = False assert loader.load(1, Optional[Union[int, str]]) == 1 assert loader.load('a', Optional[Union[int, str]]) == 'a' assert loader.load(None, Optional[Union[int, str]]) == None assert type(loader.load(1, Optional[Union[int, float]])) == int assert type(loader.load(1.0, Optional[Union[int, float]])) == float with self.assertRaises(ValueError): loader.load('', Optional[Union[int, float]]) loader.basiccast = True assert type(loader.load(1, Optional[Union[int, float]])) == int assert type(loader.load(1.0, Optional[Union[int, float]])) == float assert loader.load(None, Optional[str]) is None def test_debug_union(self): loader = dataloader.Loader() class A(NamedTuple): a: int class B(NamedTuple): a: int assert isinstance(loader.load({'a': 1}, Union[A, B]), (A, B)) loader.uniondebugconflict = True with self.assertRaises(TypeError): loader.load({'a': 1}, Union[A, B]) class TestFastIterableLoad(unittest.TestCase): def yielder(self): yield from range(2) yield "1" def test_tupleload_from_generator_with_exception(self): loader = dataloader.Loader(basiccast=False) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), Tuple[int, ...]) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), Tuple[Union[float, int], ...]) loader = dataloader.Loader(basiccast=True) assert loader.load(self.yielder(), Tuple[int, ...]) == (0, 1, 1) assert loader.load(self.yielder(), Tuple[Union[float, int], ...]) == (0, 1, 1) assert loader.load(self.yielder(), Tuple[Union[str, int], ...]) == (0, 1, '1') def test_listload_from_generator_with_exception(self): loader = dataloader.Loader(basiccast=False) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), List[int]) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), List[Union[int, float]]) loader = dataloader.Loader(basiccast=True) assert loader.load(self.yielder(), List[int]) == [0, 1, 1] assert loader.load(self.yielder(), List[Union[float, int]]) == [0, 1, 1] assert loader.load(self.yielder(), List[Union[int, str]]) == [0, 1, "1"] def test_frozensetload_from_generator_with_exception(self): loader = dataloader.Loader(basiccast=False) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), FrozenSet[int]) loader = dataloader.Loader(basiccast=True) assert loader.load(self.yielder(), FrozenSet[int]) == frozenset((0, 1, 1)) def test_setload_from_generator_with_exception(self): loader = dataloader.Loader(basiccast=False) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), Set[int]) with self.assertRaises(exceptions.TypedloadValueError): a = loader.load(self.yielder(), Set[Union[int, float]]) loader = dataloader.Loader(basiccast=True) assert loader.load(self.yielder(), Set[int]) == {0, 1, 1} assert loader.load(self.yielder(), Set[Union[float, int]]) == {0, 1, 1} assert loader.load(self.yielder(), Set[Union[int, str]]) == {0, 1, "1"} class TestTupleLoad(unittest.TestCase): def test_ellipsis(self): loader = dataloader.Loader() l = list(range(33)) t = tuple(l) assert loader.load(l, Tuple[int, ...]) == t assert loader.load('abc', Tuple[str, ...]) == ('a', 'b', 'c') assert loader.load('a', Tuple[str, ...]) == ('a', ) def test_tuple(self): loader = dataloader.Loader() with self.assertRaises(ValueError): assert loader.load([1], Tuple[int, int]) == (1, 2) assert loader.load([1, 2, 3], Tuple[int, int]) == (1, 2) loader.failonextra = True # Now the same will fail with self.assertRaises(ValueError): loader.load([1, 2, 3], Tuple[int, int]) == (1, 2) class TestNamedTuple(unittest.TestCase): def test_simple(self): class A(NamedTuple): a: int b: str loader = dataloader.Loader() r = A(1,'1') assert loader.load({'a': 1, 'b': 1}, A) == r assert loader.load({'a': 1, 'b': 1, 'c': 3}, A) == r loader.failonextra = True with self.assertRaises(TypeError): loader.load({'a': 1, 'b': 1, 'c': 3}, A) def test_simple_defaults(self): class A(NamedTuple): a: int = 1 b: str = '1' loader = dataloader.Loader() r = A(1,'1') assert loader.load({}, A) == r def test_nested(self): class A(NamedTuple): a: int class B(NamedTuple): a: A loader = dataloader.Loader() r = B(A(1)) assert loader.load({'a': {'a': 1}}, B) == r with self.assertRaises(TypeError): loader.load({'a': {'a': 1}}, A) def test_fail(self): class A(NamedTuple): a: int q: str loader = dataloader.Loader() with self.assertRaises(TypeError): loader.load({'a': 3}, A) class TestEnum(unittest.TestCase): def test_load_difficult_enum(self): class TestEnum(Enum): A: int = 1 B: Tuple[int,int,int] = (1, 2, 3) loader = dataloader.Loader() assert loader.load(1, TestEnum) == TestEnum.A assert loader.load((1, 2, 3), TestEnum) == TestEnum.B assert loader.load([1, 2, 3], TestEnum) == TestEnum.B assert loader.load([1, 2, 3, 4], TestEnum) == TestEnum.B loader.failonextra = True with self.assertRaises(ValueError): loader.load([1, 2, 3, 4], TestEnum) def test_load_enum(self): loader = dataloader.Loader() class TestEnum(Enum): LABEL1 = 1 LABEL2 = '2' assert loader.load(1, TestEnum) == TestEnum.LABEL1 assert loader.load('2', TestEnum) == TestEnum.LABEL2 with self.assertRaises(ValueError): loader.load(2, TestEnum) assert loader.load(['2', 1], Tuple[TestEnum, TestEnum]) == (TestEnum.LABEL2, TestEnum.LABEL1) class TestForwardRef(unittest.TestCase): def test_known_refs(self): class Node(NamedTuple): value: int = 1 next: Optional['Node'] = None l = {'next': {}, 'value': 12} loader = dataloader.Loader() assert loader.load(l, Node) == Node(value=12,next=Node()) def test_disable(self): class A(NamedTuple): i: 'int' loader = dataloader.Loader(frefs=None) with self.assertRaises(Exception): loader.load(3, A) def test_add_fref(self): class A(NamedTuple): i: 'alfio' loader = dataloader.Loader() with self.assertRaises(ValueError): loader.load({'i': 3}, A) loader.frefs['alfio'] = int assert loader.load({'i': 3}, A) == A(3) class TestLoaderIndex(unittest.TestCase): def test_removal(self): loader = dataloader.Loader() assert loader.load(3, int) == 3 loader = dataloader.Loader() loader.handlers.pop(loader.index(int)) with self.assertRaises(TypeError): loader.load(3, int) class TestExceptions(unittest.TestCase): def test_dict_is_not_list(self): loader = dataloader.Loader() with self.assertRaises(exceptions.TypedloadTypeError): loader.load({1: 1}, List[int]) with self.assertRaises(exceptions.TypedloadTypeError): loader.load({1: 1}, Tuple[int, ...]) with self.assertRaises(exceptions.TypedloadTypeError): loader.load({1: 1}, Set[int]) def test_dict_exception(self): loader = dataloader.Loader() with self.assertRaises(exceptions.TypedloadAttributeError): loader.load(None, Dict[int, int]) def test_index(self): loader = dataloader.Loader() try: loader.load([1, 2, 3, 'q'], List[int]) except Exception as e: assert e.trace[-1].annotation[1] == 3 try: loader.load(['q', 2], Tuple[int,int]) except Exception as e: assert e.trace[-1].annotation[1] == 0 try: loader.load({'q': 1}, Dict[int,int]) except Exception as e: assert e.trace[-1].annotation[1] == 'q' def test_attrname(self): class A(NamedTuple): a: int class B(NamedTuple): a: A b: int loader = dataloader.Loader() try: loader.load({'a': 'q'}, A) except Exception as e: assert e.trace[-1].annotation[1] == 'a' try: loader.load({'a':'q','b': 1}, B) except Exception as e: print(e.trace) assert e.trace[-1].annotation[1] == 'a' try: loader.load({'a':3,'b': 1}, B) except Exception as e: assert e.trace[-1].annotation[1] == 'a' def test_typevalue(self): loader = dataloader.Loader() try: loader.load([1, 2, 3, 'q'], List[int]) except Exception as e: assert e.value == 'q' assert e.type_ == int class TestDictEquivalence(unittest.TestCase): def test_namespace(self): loader = dataloader.Loader() data = argparse.Namespace(a=12, b='33') class A(NamedTuple): a: int b: int c: int = 1 assert loader.load(data, A) == A(12, 33, 1) assert loader.load(data, Dict[str, int]) == {'a': 12, 'b': 33} def test_nonamespace(self): loader = dataloader.Loader(dictequivalence=False) data = argparse.Namespace(a=1) with self.assertRaises(AttributeError): loader.load(data, Dict[str, int]) class TestCommonTypes(unittest.TestCase): def test_path(self): loader = dataloader.Loader() assert loader.load('/', Path) == Path('/') def test_pattern_str(self): loader = dataloader.Loader() if sys.version_info[:2] <= (3, 8): with self.assertRaises(TypeError): assert loader.load(r'[bc](at|ot)\d+', re.Pattern[str]) else: assert loader.load(r'[bc](at|ot)\d+', re.Pattern[str]) == re.compile(r'[bc](at|ot)\d+') assert loader.load(r'[bc](at|ot)\d+', typing.Pattern[str]) == re.compile(r'[bc](at|ot)\d+') def test_pattern_bytes(self): loader = dataloader.Loader() if sys.version_info[:2] <= (3, 8): with self.assertRaises(TypeError): assert loader.load(br'[bc](at|ot)\d+', re.Pattern[bytes]) else: assert loader.load(br'[bc](at|ot)\d+', re.Pattern[bytes]) == re.compile(br'[bc](at|ot)\d+') assert loader.load(br'[bc](at|ot)\d+', typing.Pattern[bytes]) == re.compile(br'[bc](at|ot)\d+') def test_pattern(self): loader = dataloader.Loader() assert loader.load(r'[bc](at|ot)\d+', re.Pattern) == re.compile(r'[bc](at|ot)\d+') assert loader.load(br'[bc](at|ot)\d+', re.Pattern) == re.compile(br'[bc](at|ot)\d+') assert loader.load(r'[bc](at|ot)\d+', typing.Pattern) == re.compile(r'[bc](at|ot)\d+') assert loader.load(br'[bc](at|ot)\d+', typing.Pattern) == re.compile(br'[bc](at|ot)\d+') # Right type, invalid value with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(r'((((((', re.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(br'((((((', re.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(r'((((((', typing.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(br'((((((', typing.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(r'(?P[bc])(?P(at|ot))\d+', re.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(br'(?P[bc])(?P(at|ot))\d+', re.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(r'(?P[bc])(?P(at|ot))\d+', typing.Pattern) with self.assertRaises(exceptions.TypedloadException) as e: assert loader.load(br'(?P[bc])(?P(at|ot))\d+', typing.Pattern) # Wrong type with self.assertRaises(exceptions.TypedloadTypeError) as e: assert loader.load(33, re.Pattern) with self.assertRaises(exceptions.TypedloadTypeError) as e: assert loader.load(33, typing.Pattern) with self.assertRaises(exceptions.TypedloadTypeError) as e: assert loader.load(False, re.Pattern) with self.assertRaises(exceptions.TypedloadTypeError) as e: assert loader.load(False, typing.Pattern) with self.assertRaises(exceptions.TypedloadTypeError) as e: assert loader.load(None, re.Pattern) with self.assertRaises(exceptions.TypedloadTypeError) as e: assert loader.load(None, typing.Pattern) def test_uuid(self): loader = dataloader.Loader() assert loader.load('631b09cb-016e-11ef-97ce-000000000001', UUID) == UUID('631b09cb-016e-11ef-97ce-000000000001') # Invalid UUID with self.assertRaises(ValueError): loader.load('631b09cb-016e-11ef-97ce-00000000000', UUID) def test_ipaddress(self): loader = dataloader.Loader() assert loader.load('10.10.10.1', IPv4Address) == IPv4Address('10.10.10.1') assert loader.load('10.10.10.1', IPv4Network) == IPv4Network('10.10.10.1/32') assert loader.load('10.10.10.1', IPv4Interface) == IPv4Interface('10.10.10.1/32') assert loader.load('fe80::123', IPv6Address) == IPv6Address('fe80::123') assert loader.load('10.10.10.0/24', IPv4Network) == IPv4Network('10.10.10.0/24') assert loader.load('fe80::/64', IPv6Network) == IPv6Network('fe80::/64') assert loader.load('10.10.10.1/24', IPv4Interface) == IPv4Interface('10.10.10.1/24') assert loader.load('fe80::123/64', IPv6Interface) == IPv6Interface('fe80::123/64') # Wrong IP version with self.assertRaises(ValueError): loader.load('10.10.10.1', IPv6Address) with self.assertRaises(ValueError): loader.load('fe80::123', IPv4Address) with self.assertRaises(ValueError): loader.load('10.10.10.0/24', IPv6Network) with self.assertRaises(ValueError): loader.load('fe80::123', IPv4Network) with self.assertRaises(ValueError): loader.load('10.10.10.1/24', IPv6Interface) with self.assertRaises(ValueError): loader.load('fe80::123/64', IPv4Interface) # Wrong ipaddress type with self.assertRaises(ValueError): loader.load('10.10.10.1/24', IPv4Address) with self.assertRaises(ValueError): loader.load('10.10.10.1/24', IPv4Network) class TestAny(unittest.TestCase): def test_any(self): loader = dataloader.Loader() o = object() assert loader.load(o, Any) is o class TestNewType(unittest.TestCase): def test_newtype(self): loader = dataloader.Loader() Foo = NewType("Foo", str) bar = loader.load("bar", Foo) assert bar == "bar" assert type(bar) is str typedload/tests/__main__.py0000664000175000017500000000317614721335070015344 0ustar salvosalvo# typedload # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import unittest import sys print('Running tests using %s' % sys.version) if sys.version_info.major != 3 or sys.version_info.minor < 9: raise Exception('Only version 3.9 and above supported') from .test_dataloader import * from .test_datadumper import * from .test_dumpload import * from .test_exceptions import * from .test_dataclass import * from .test_deferred import * from .test_legacytuples_dataloader import * from .test_typechecks import * from .test_datetime import * from .test_literal import * from .test_typeddict import * if sys.version_info.minor >= 10: from .test_orunion import * if sys.version_info.minor >= 12: from .test_typealias import * # Run tests for attr only if it is installed try: import attr attr_module = True except ImportError: attr_module = False if attr_module: from .test_attrload import * if __name__ == '__main__': unittest.main() typedload/tests/test_legacytuples_dataloader.py0000664000175000017500000002101214721335070021531 0ustar salvosalvo# typedload # Copyright (C) 2018 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from enum import Enum from typing import Dict, FrozenSet, List, NamedTuple, Optional, Set, Tuple, Union import unittest from typedload import dataloader, load class TestLegacy_oldsyntax(unittest.TestCase): def test_legacyload(self): A = NamedTuple('A', [('a', int), ('b', str)]) assert load({'a': 101, 'b': 'ciao'}, A) == A(101, 'ciao') def test_nestedlegacyload(self): A = NamedTuple('A', [('a', int), ('b', str)]) B = NamedTuple('B', [('a', A), ('b', List[A])]) assert load({'a': {'a': 101, 'b': 'ciao'}, 'b': []}, B) == B(A(101, 'ciao'), []) assert load( {'a': {'a': 101, 'b': 'ciao'}, 'b': [{'a': 1, 'b': 'a'},{'a': 0, 'b': 'b'}]}, B ) == B(A(101, 'ciao'), [A(1, 'a'),A(0, 'b')]) class TestUnion_oldsyntax(unittest.TestCase): def test_ComplicatedUnion(self): A = NamedTuple('A', [('a', int)]) B = NamedTuple('B', [('a', str)]) C = NamedTuple('C', [('val', Union[A, B])]) loader = dataloader.Loader() loader.basiccast = False assert type(loader.load({'val': {'a': 1}}, C).val) == A assert type(loader.load({'val': {'a': '1'}}, C).val) == B def test_optional(self): loader = dataloader.Loader() assert loader.load(1, Optional[int]) == 1 assert loader.load(None, Optional[int]) == None assert loader.load('1', Optional[int]) == 1 with self.assertRaises(ValueError): loader.load('ciao', Optional[int]) loader.basiccast = False loader.load('1', Optional[int]) def test_union(self): loader = dataloader.Loader() loader.basiccast = False assert loader.load(1, Optional[Union[int, str]]) == 1 assert loader.load('a', Optional[Union[int, str]]) == 'a' assert loader.load(None, Optional[Union[int, str]]) == None assert type(loader.load(1, Optional[Union[int, float]])) == int assert type(loader.load(1.0, Optional[Union[int, float]])) == float with self.assertRaises(ValueError): loader.load('', Optional[Union[int, float]]) loader.basiccast = True assert type(loader.load(1, Optional[Union[int, float]])) == int assert type(loader.load(1.0, Optional[Union[int, float]])) == float assert loader.load(None, Optional[str]) is None class TestNamedTuple_oldsyntax(unittest.TestCase): def test_simple(self): A = NamedTuple('A', [('a', int), ('b', str)]) loader = dataloader.Loader() r = A(1,'1') assert loader.load({'a': 1, 'b': 1}, A) == r assert loader.load({'a': 1, 'b': 1, 'c': 3}, A) == r loader.failonextra = True with self.assertRaises(TypeError): loader.load({'a': 1, 'b': 1, 'c': 3}, A) def test_nested(self): A = NamedTuple('A', [('a', int)]) B = NamedTuple('B', [('a', A)]) loader = dataloader.Loader() r = B(A(1)) assert loader.load({'a': {'a': 1}}, B) == r with self.assertRaises(TypeError): loader.load({'a': {'a': 1}}, A) def test_fail(self): A = NamedTuple('A', [('a', int), ('q', str)]) loader = dataloader.Loader() with self.assertRaises(TypeError): loader.load({'a': 3}, A) class TestSet(unittest.TestCase): def test_load_set(self): loader = dataloader.Loader() r = {(1, 1), (2, 2), (0, 0)} assert loader.load(zip(range(3), range(3)), Set[Tuple[int,int]]) == r assert loader.load([1, '2', 2], Set[int]) == {1, 2} def test_load_frozen_set(self): loader = dataloader.Loader() assert loader.load(range(4), FrozenSet[float]) == frozenset((0.0, 1.0, 2.0, 3.0)) class TestDict(unittest.TestCase): def test_load_dict(self): loader = dataloader.Loader() class State(Enum): OK = 'ok' FAILED = 'failed' v = {'1': 'ok', '15': 'failed'} r = {1: State.OK, 15: State.FAILED} assert loader.load(v, Dict[int, State]) == r def test_load_nondict(self): class SimDict(): def items(self): return zip(range(12), range(12)) loader = dataloader.Loader() assert loader.load(SimDict(), Dict[str, int]) == {str(k): v for k,v in zip(range(12), range(12))} with self.assertRaises(AttributeError): loader.load(33, Dict[int, str]) class TestTuple(unittest.TestCase): def test_load_list_of_tuples(self): t = List[Tuple[str, int, Tuple[int, int]]] v = [ ['a', 12, [1, 1]], ['b', 15, [3, 2]], ] r = [ ('a', 12, (1, 1)), ('b', 15, (3, 2)), ] loader = dataloader.Loader() assert loader.load(v, t) == r def test_load_nested_tuple(self): loader = dataloader.Loader() assert loader.load([1, 2, 3, [1, 2]], Tuple[int,int,int,Tuple[str,str]]) == (1, 2, 3, ('1', '2')) def test_load_tuple(self): loader = dataloader.Loader() assert loader.load([1, 2, 3], Tuple[int,int,int]) == (1, 2, 3) assert loader.load(['2', False, False], Tuple[int, bool]) == (2, False) with self.assertRaises(ValueError): loader.load(['2', False], Tuple[int, bool, bool]) loader.failonextra = True assert loader.load(['2', False, False], Tuple[int, bool]) == (2, False) class TestLoader(unittest.TestCase): def test_kwargs(self): with self.assertRaises(ValueError): load(1, str, basiccast=False) load(1, int, handlers=[]) class TestBasicTypes(unittest.TestCase): def test_basic_casting(self): # Casting enabled, by default loader = dataloader.Loader() assert loader.load(1, int) == 1 assert loader.load(1.1, int) == 1 assert loader.load(False, int) == 0 assert loader.load('ciao', str) == 'ciao' assert loader.load('1', float) == 1.0 with self.assertRaises(ValueError): loader.load('ciao', float) def test_list_basic(self): loader = dataloader.Loader() assert loader.load(range(12), List[int]) == list(range(12)) assert loader.load(range(12), List[str]) == [str(i) for i in range(12)] def test_extra_basic(self): # Add more basic types loader = dataloader.Loader() with self.assertRaises(TypeError): assert loader.load(b'ciao', bytes) == b'ciao' loader.basictypes.add(bytes) assert loader.load(b'ciao', bytes) == b'ciao' def test_none_basic(self): loader = dataloader.Loader() loader.load(None, type(None)) with self.assertRaises(ValueError): loader.load(12, type(None)) def test_basic_nocasting(self): # Casting enabled, by default loader = dataloader.Loader() loader.basiccast = False assert loader.load(1, int) == 1 assert loader.load(True, bool) == True assert loader.load(1.5, float) == 1.5 with self.assertRaises(ValueError): loader.load(1.1, int) loader.load(False, int) loader.load('ciao', str) loader.load('1', float) class TestHandlers(unittest.TestCase): def test_custom_handler(self): class Q: def __eq__(self, other): return isinstance(other, Q) loader = dataloader.Loader() loader.handlers.append(( lambda t: t == Q, lambda l, v, t: Q() )) assert loader.load('test', Q) == Q() def test_broken_handler(self): loader = dataloader.Loader() loader.handlers.insert(0, (lambda t: 33 + t is None, lambda l, v, t: None)) with self.assertRaises(TypeError): loader.load(1, int) loader.raiseconditionerrors = False assert loader.load(1, int) == 1 typedload/tests/test_deferred.py0000664000175000017500000000327614721335070016444 0ustar salvosalvo# typedload # Copyright (C) 2022 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from __future__ import annotations from dataclasses import dataclass from typing import NamedTuple, Optional import unittest from typedload import load class A(NamedTuple): a: Optional[int] @dataclass class B: a: Optional[int] class TestDeferred(unittest.TestCase): ''' This test should entirely be deleted when the PEP is superseeded. ''' def test_deferred_named_tuple(self): assert load({'a': None}, A, pep563=True) == A(None) assert load({'a': 3}, A, pep563=True) == A(3) with self.assertRaises(ValueError): load({'a': None}, A) with self.assertRaises(ValueError): load({'a': 3}, A) def test_deferred_dataclass(self): assert load({'a': None}, B, pep563=True) == B(None) assert load({'a': 3}, B, pep563=True) == B(3) with self.assertRaises(TypeError): load({'a': None}, B) with self.assertRaises(TypeError): load({'a': 3}, B) typedload/tests/mypy_literaldirect.py0000664000175000017500000000021614721335070017521 0ustar salvosalvoimport typedload from typing import * typedload.load("a", Literal["a"]) def wantint(i: int) -> None: ... wantint(typedload.load("3", int)) typedload/tests/test_typechecks.py0000664000175000017500000002063414721335070017023 0ustar salvosalvo# typedload # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from enum import Enum from typing import Dict, FrozenSet, List, NamedTuple, Optional, Set, Tuple, Union, Any, NewType, Literal import unittest import sys from typedload import typechecks class TestChecks(unittest.TestCase): def test_is_readonly(self): assert (not typechecks.is_readonly(None)) # Only from 3.13 if sys.version_info.minor < 13: return from typing import ReadOnly assert typechecks.is_readonly(ReadOnly[int]) assert typechecks.is_readonly(ReadOnly[str]) assert typechecks.is_readonly(ReadOnly[Union[int, str]]) assert not typechecks.is_readonly(list[int]) assert not typechecks.is_readonly(list[str]) assert not typechecks.is_readonly(list[Union[int, str]]) def test_readonly(self): # Only from 3.13 if sys.version_info.minor < 13: return from typing import ReadOnly assert int == typechecks.readonlytype(ReadOnly[int]) def test_is_not_required(self): if sys.version_info.minor >= 11: from typing import NotRequired, Required assert typechecks.is_notrequired(NotRequired[int]) assert typechecks.is_notrequired(NotRequired[str]) assert typechecks.is_notrequired(NotRequired[Union[int, str]]) assert not typechecks.is_notrequired(Required[int]) assert not typechecks.is_notrequired(Required[str]) assert not typechecks.is_notrequired(Required[Union[int, str]]) assert (not typechecks.is_notrequired(None)) def test_is_required(self): if sys.version_info.minor >= 11: from typing import NotRequired, Required assert typechecks.is_required(Required[int]) assert typechecks.is_required(Required[str]) assert typechecks.is_required(Required[Union[int, str]]) assert not typechecks.is_required(NotRequired[int]) assert not typechecks.is_required(NotRequired[str]) assert not typechecks.is_required(NotRequired[Union[int, str]]) assert (not typechecks.is_required(None)) def test_not_required(self): if sys.version_info.minor < 11: # Only from 3.11 return from typing import NotRequired assert int == typechecks.notrequiredtype(NotRequired[int]) def test_required(self): if sys.version_info.minor < 11: # Only from 3.11 return from typing import Required assert int == typechecks.requiredtype(Required[int]) def test_literalvalues(self): l = Literal[1, 2, 3] assert 1 in typechecks.literalvalues(l) assert 2 in typechecks.literalvalues(l) assert 3 in typechecks.literalvalues(l) assert 4 not in typechecks.literalvalues(l) def test_is_literal(self): l = Literal[1, 2, 3] assert typechecks.is_literal(l) assert not typechecks.is_literal(3) assert not typechecks.is_literal(int) assert not typechecks.is_literal(str) assert not typechecks.is_literal(None) assert not typechecks.is_literal(List[int]) def test_is_not_typeddict(self): assert not typechecks.is_typeddict(int) assert not typechecks.is_typeddict(3) assert not typechecks.is_typeddict(str) assert not typechecks.is_typeddict({}) assert not typechecks.is_typeddict(dict) assert not typechecks.is_typeddict(set) assert not typechecks.is_typeddict(None) assert not typechecks.is_typeddict(List[str]) def test_is_list(self): assert typechecks.is_list(List) assert typechecks.is_list(List[int]) assert typechecks.is_list(List[str]) assert not typechecks.is_list(list) assert not typechecks.is_list(Tuple[int, str]) assert not typechecks.is_list(Dict[int, str]) assert not typechecks.is_list([]) assert typechecks.is_list(list[str]) assert not typechecks.is_list(tuple[str]) def test_is_dict(self): assert typechecks.is_dict(Dict[int, int]) assert typechecks.is_dict(Dict) assert typechecks.is_dict(Dict[str, str]) assert not typechecks.is_dict(Tuple[str, str]) assert not typechecks.is_dict(Set[str]) assert typechecks.is_dict(dict[str, str]) assert not typechecks.is_dict(tuple[str]) def test_is_set(self): assert typechecks.is_set(Set[int]) assert typechecks.is_set(Set) assert typechecks.is_set(set[str]) assert not typechecks.is_set(tuple[str]) def test_is_frozenset_(self): assert not typechecks.is_frozenset(Set[int]) assert typechecks.is_frozenset(FrozenSet[int]) assert typechecks.is_frozenset(FrozenSet) assert typechecks.is_frozenset(frozenset[str]) assert not typechecks.is_frozenset(tuple[str]) def test_is_tuple(self): assert typechecks.is_tuple(Tuple[str, int, int]) assert typechecks.is_tuple(Tuple) assert not typechecks.is_tuple(tuple) assert not typechecks.is_tuple((1,2)) assert typechecks.is_tuple(tuple[str]) assert not typechecks.is_tuple(list[str]) def test_is_union(self): assert typechecks.is_union(Optional[int]) assert typechecks.is_union(Optional[str]) assert typechecks.is_union(Union[bytes, str]) assert typechecks.is_union(Union[str, int, float]) assert not typechecks.is_union(FrozenSet[int]) assert not typechecks.is_union(int) def test_is_optional(self): assert typechecks.is_optional(Optional[int]) assert typechecks.is_optional(Optional[str]) assert not typechecks.is_optional(Union[bytes, str]) assert not typechecks.is_optional(Union[str, int, float]) assert not typechecks.is_union(FrozenSet[int]) assert not typechecks.is_union(int) def test_is_nonetype(self): assert typechecks.is_nonetype(type(None)) assert not typechecks.is_nonetype(List[int]) def test_is_enum(self): class A(Enum): BB = 3 assert typechecks.is_enum(A) assert not typechecks.is_enum(Set[int]) def test_is_namedtuple(self): A = NamedTuple('A', [ ('val', int), ]) assert typechecks.is_namedtuple(A) assert not typechecks.is_namedtuple(Tuple) assert not typechecks.is_namedtuple(tuple) assert not typechecks.is_namedtuple(Tuple[int, int]) def test_is_forwardref(self): try: # Since 3.7 from typing import ForwardRef # type: ignore except ImportError: from typing import _ForwardRef as ForwardRef # type: ignore assert typechecks.is_forwardref(ForwardRef('SomeType')) def test_uniontypes(self): assert set(typechecks.uniontypes(Optional[bool])) == {typechecks.NONETYPE, bool} assert set(typechecks.uniontypes(Optional[int])) == {typechecks.NONETYPE, int} assert set(typechecks.uniontypes(Optional[Union[int, float]])) == {typechecks.NONETYPE, float, int} assert set(typechecks.uniontypes(Optional[Union[int, str, Optional[float]]])) == {typechecks.NONETYPE, str, int, float} with self.assertRaises(AttributeError): typechecks.uniontypes(Union[int]) def test_any(self): assert typechecks.is_any(Any) assert not typechecks.is_any(str) assert not typechecks.is_any(Tuple[int, ...]) assert not typechecks.is_any(int) assert not typechecks.is_any(List[float]) def test_isnewtype(self): assert typechecks.is_newtype(NewType("foo", str)) assert not typechecks.is_newtype(type(NewType("foo", str)("bar"))) assert not typechecks.is_typeddict(str) typedload/tests/test_dataclass.py0000664000175000017500000001531114721335070016614 0ustar salvosalvo# typedload # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union import unittest import sys from typedload import dataloader, load, dump, typechecks, exceptions class TestDataclassLoad(unittest.TestCase): def test_do_not_init(self): @dataclass class Q: a: int b: int c: int = field(init=False) def __post_init__(self): self.c = self.a + self.b assert typechecks.is_dataclass(Q) assert load({'a': 1, 'b': 2}, Q).c == 3 a = load({'a': 12, 'b': 30}, Q) assert a.c == 42 a.c = 1 assert a.c == 1 assert a.a == 12 assert a.b == 30 def test_missing(self): @dataclass class A: a: int with self.assertRaises(TypeError): load({}, A) def test_is_dataclass(self): @dataclass class A: pass class B(NamedTuple): pass assert typechecks.is_dataclass(A) assert not typechecks.is_dataclass(List[int]) assert not typechecks.is_dataclass(Tuple[int, int]) assert not typechecks.is_dataclass(B) def test_factory_load(self): @dataclass class A: a: List[int] = field(default_factory=list) assert load({'a': [1, 2, 3]}, A) == A([1, 2, 3]) assert load({'a': []}, A) == A() assert load({}, A) == A() def test_load(self): @dataclass class A: a: int b: str assert load({'a': 101, 'b': 'ciao'}, A) == A(101, 'ciao') if sys.version_info.minor >= 10: def test_loadslotted(self): @dataclass(slots=True) class A: a: int assert load({'a': 1}, A) == A(1) def test_nestedload(self): @dataclass class A: a: int b: str @dataclass class B: a: A b: List[A] assert load({'a': {'a': 101, 'b': 'ciao'}, 'b': []}, B) == B(A(101, 'ciao'), []) assert load( {'a': {'a': 101, 'b': 'ciao'}, 'b': [{'a': 1, 'b': 'a'},{'a': 0, 'b': 'b'}]}, B ) == B(A(101, 'ciao'), [A(1, 'a'),A(0, 'b')]) def test_defaultvalue(self): @dataclass class A: a: int b: Optional[str] = None assert load({'a': 1}, A) == A(1) assert load({'a': 1, 'b': 'io'}, A) == A(1, 'io') class TestDataclassUnion(unittest.TestCase): def test_ComplicatedUnion(self): @dataclass class A: a: int @dataclass class B: a: str @dataclass class C: val: Union[A, B] loader = dataloader.Loader() loader.basiccast = False assert type(loader.load({'val': {'a': 1}}, C).val) == A assert type(loader.load({'val': {'a': '1'}}, C).val) == B # This class has to be defined at the top-level of the module to be visible by get_type_hints # when it resolves the "Node" string annotation. @dataclass class Node: name: str child: Optional["Node"] = None class TestDataclassDump(unittest.TestCase): def test_dump(self): @dataclass class A: a: int b: int = 0 assert dump(A(12)) == {'a': 12} assert dump(A(12), hidedefault=False) == {'a': 12, 'b': 0} if sys.version_info.minor >= 10: def test_dump_slots(self): @dataclass(slots=True) class A: a: int assert dump(A(1)) == {'a': 1} def test_factory_dump(self): @dataclass class A: a: int b: List[int] = field(default_factory=list) assert dump(A(3)) == {'a': 3} assert dump(A(12), hidedefault=False) == {'a': 12, 'b': []} def test_cyclic_dump(self): assert dump(Node("foo")) == {"name": "foo"} assert dump(Node("foo", child=Node("bar"))) == { "name": "foo", "child": {"name": "bar"}, } class TestDataclassMangle(unittest.TestCase): def test_mangle_extra(self): @dataclass class Mangle: value: int = field(metadata={'name': 'Value'}) assert load({'value': 12, 'Value': 12}, Mangle) == Mangle(12) with self.assertRaises(exceptions.TypedloadValueError): load({'value': 12, 'Value': 12}, Mangle, failonextra=True) def test_mangle_load(self): @dataclass class Mangle: value: int = field(metadata={'name': 'va.lue'}) assert load({'va.lue': 1}, Mangle) == Mangle(1) assert dump(Mangle(1)) == {'va.lue': 1} def test_case(self): @dataclass class Mangle: value: int = field(metadata={'name': 'Value'}) assert load({'Value': 1}, Mangle) == Mangle(1) assert 'Value' in dump(Mangle(1)) with self.assertRaises(TypeError): load({'value': 1}, Mangle) def test_mangle_rename(self): @dataclass class Mangle: a: int = field(metadata={'name': 'b'}) b: str = field(metadata={'name': 'a'}) assert load({'b': 1, 'a': 'ciao'}, Mangle) == Mangle(1, 'ciao') assert dump(Mangle(1, 'ciao')) == {'b': 1, 'a': 'ciao'} def test_weird_mangle(self): @dataclass class Mangle: a: int = field(metadata={'name': 'b', 'alt': 'q'}) b: str = field(metadata={'name': 'a'}) assert load({'b': 1, 'a': 'ciao'}, Mangle) == Mangle(1, 'ciao') assert load({'q': 1, 'b': 'ciao'}, Mangle, mangle_key='alt') == Mangle(1, 'ciao') assert dump(Mangle(1, 'ciao')) == {'b': 1, 'a': 'ciao'} assert dump(Mangle(1, 'ciao'), mangle_key='alt') == {'q': 1, 'b': 'ciao'} def test_correct_exception_when_mangling(self): @dataclass class A: a: str = field(metadata={'name': 'q'}) with self.assertRaises(exceptions.TypedloadAttributeError): load(1, A) typedload/tests/test_attrload.py0000664000175000017500000002151514721335070016472 0ustar salvosalvo# typedload # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from enum import Enum from typing import Dict, List, NamedTuple, Optional, Set, Tuple, Union import unittest import sys from attr import attrs, attrib, define, field from typedload import load, dump, exceptions, typechecks from typedload import datadumper class Hair(Enum): BROWN = 'brown' BLACK = 'black' BLONDE = 'blonde' WHITE = 'white' @attrs class Person: name = attrib(default='Turiddu', type=str) address = attrib(type=Optional[str], default=None) @attrs class DetailedPerson(Person): hair = attrib(type=Hair, default=Hair.BLACK) @attrs class Students: course = attrib(type=str) students = attrib(type=List[Person]) @attrs class Mangle: value = attrib(type=int, metadata={'name': 'va.lue'}) class TestAttrDump(unittest.TestCase): def test_basicdump(self): assert dump(Person()) == {} assert dump(Person('Alfio')) == {'name': 'Alfio'} assert dump(Person('Alfio', '33')) == {'name': 'Alfio', 'address': '33'} def test_norepr(self): @attrs class A: i = attrib(type=int) j = attrib(type=int, repr=False) assert dump(A(1,1)) == {'i': 1} def test_dumpdefault(self): dumper = datadumper.Dumper() dumper.hidedefault = False assert dumper.dump(Person()) == {'name': 'Turiddu', 'address': None} def test_factory_dump(self): @attrs class A: a = attrib(factory=list, metadata={'ciao': 'ciao'}, type=List[int]) assert dump(A()) == {} assert dump(A(), hidedefault=False) == {'a': []} def test_nesteddump(self): assert dump( Students('advanced coursing', [ Person('Alfio'), Person('Carmelo', 'via mulino'), ])) == { 'course': 'advanced coursing', 'students': [ {'name': 'Alfio'}, {'name': 'Carmelo', 'address': 'via mulino'}, ] } class TestAttrload(unittest.TestCase): def test_condition(self): assert typechecks.is_attrs(Person) assert typechecks.is_attrs(Students) assert typechecks.is_attrs(Mangle) assert typechecks.is_attrs(DetailedPerson) assert not typechecks.is_attrs(int) assert not typechecks.is_attrs(List[int]) assert not typechecks.is_attrs(Union[str, int]) assert not typechecks.is_attrs(Tuple[str, int]) def test_basicload(self): assert load({'name': 'gino'}, Person) == Person('gino') assert load({}, Person) == Person('Turiddu') def test_nestenum(self): assert load({'hair': 'white'}, DetailedPerson) == DetailedPerson(hair=Hair.WHITE) def test_nested(self): assert load( { 'course': 'advanced coursing', 'students': [ {'name': 'Alfio'}, {'name': 'Carmelo', 'address': 'via mulino'}, ] }, Students, ) == Students('advanced coursing', [ Person('Alfio'), Person('Carmelo', 'via mulino'), ]) def test_uuid(self): import uuid @attrs class A: a = attrib(type=int) uuid_value = attrib(type=str, init=False) def __attrs_post_init__(self): self.uuid_value = str(uuid.uuid4()) assert type(load({'a': 1}, A).uuid_value) == str assert load({'a': 1}, A) != load({'a': 1}, A) class TestMangling(unittest.TestCase): def test_mangle_extra(self): @attrs class Mangle: value = attrib(metadata={'name': 'Value'}, type=int) assert load({'value': 12, 'Value': 12}, Mangle) == Mangle(12) with self.assertRaises(exceptions.TypedloadValueError): load({'value': 12, 'Value': 12}, Mangle, failonextra=True) def test_load_metanames(self): a = {'va.lue': 12} b = a.copy() assert load(a, Mangle) == Mangle(12) assert a == b def test_case(self): @attrs class Mangle: value = attrib(type = int, metadata={'name': 'Value'}) assert load({'Value': 1}, Mangle) == Mangle(1) assert 'Value' in dump(Mangle(1)) with self.assertRaises(TypeError): load({'value': 1}, Mangle) def test_dump_metanames(self): assert dump(Mangle(12)) == {'va.lue': 12} def test_mangle_rename(self): @attrs class Mangle: a = attrib(type=int, metadata={'name': 'b'}) b = attrib(type=str, metadata={'name': 'a'}) assert load({'b': 1, 'a': 'ciao'}, Mangle) == Mangle(1, 'ciao') assert dump(Mangle(1, 'ciao')) == {'b': 1, 'a': 'ciao'} def test_weird_mangle(self): @attrs class Mangle: a = attrib(type=int, metadata={'name': 'b', 'alt': 'q'}) b = attrib(type=str, metadata={'name': 'a'}) assert load({'b': 1, 'a': 'ciao'}, Mangle) == Mangle(1, 'ciao') assert load({'q': 1, 'b': 'ciao'}, Mangle, mangle_key='alt') == Mangle(1, 'ciao') assert dump(Mangle(1, 'ciao')) == {'b': 1, 'a': 'ciao'} assert dump(Mangle(1, 'ciao'), mangle_key='alt') == {'q': 1, 'b': 'ciao'} def test_correct_exception_when_mangling(self): @attrs class A: a = attrib(type=str, metadata={'name': 'q'}) with self.assertRaises(exceptions.TypedloadAttributeError): load(1, A) class TestAttrExceptions(unittest.TestCase): def test_wrongtype_simple(self): try: load(3, Person) except exceptions.TypedloadAttributeError: pass def test_wrongtype_nested(self): data = { 'course': 'how to be a corsair', 'students': [ {'name': 'Alfio'}, 3 ] } try: load(data, Students) except exceptions.TypedloadAttributeError as e: assert e.trace[-1].annotation[1] == 1 def test_index(self): try: load( { 'course': 'advanced coursing', 'students': [ {'name': 'Alfio'}, {'name': 'Carmelo', 'address': 'via mulino'}, [], ] }, Students, ) except Exception as e: assert e.trace[-2].annotation[1] == 'students' assert e.trace[-1].annotation[1] == 2 def test_needed_missing(self): @attrs class A: a: int = attrib() b: int = attrib() load({'a':1, 'b': 2}, A) with self.assertRaises(exceptions.TypedloadTypeError): load({}, A) with self.assertRaises(exceptions.TypedloadTypeError): load({'a':1}, A) class TestAttrConverter(unittest.TestCase): def test_old_style_int_conversion_any(self): @attrs class C: a: int = attrib(converter=int) b: int = attrib() assert load({'a': '1', 'b': 1}, C) == C(1, 1) with self.assertRaises(ValueError): load({'a': 'a', 'b': 1}, C) def test_new_style_int_conversion_any(self): @define class C: a: int = field(converter=int) b: int assert load({'a': '1', 'b': 1}, C) == C(1, 1) with self.assertRaises(ValueError): load({'a': 'a', 'b': 1}, C) def test_typed_conversion(self): from typing import Literal @define class A: type: Literal['A'] value: int @define class B: type: Literal['B'] value: str def conv(param: Union[A, B]) -> B: if isinstance(param, B): return param return B('B', str(param.value)) @define class Outer: inner: B = field(converter=conv) v = load({'inner': {'type': 'A', 'value': 33}}, Outer) assert v.inner.type == 'B' assert v.inner.value == '33' v = load({'inner': {'type': 'B', 'value': '33'}}, Outer) assert v.inner.type == 'B' assert v.inner.value == '33' typedload/docs/0000775000175000017500000000000014721335070013031 5ustar salvosalvotypedload/docs/comparisons.md0000664000175000017500000001145014721335070015711 0ustar salvosalvoComparisons =========== In this section we compare typedload to other similar libraries. In general, the advantages of typedload over competing libraries are: * Easy to use * Very fast when Unions are involved * Works with existing codebase and uses standard types. No inheritance or decorators * Easy to extend, even with objects from 3rd party libraries * Stable API, breaking changes only happen on major releases (it has happened once since 2018 and most users didn't notice) * Mypy and similar work without plugins * Can use and convert camelCase and snake_case * Functional approach * Pure Python, no compiling * No CVEs due to being pure python, (unlike similar projects)[https://lwn.net/Articles/998043/] * Very small, it's fast for automated tests to download, extract and install compared to huge binary libraries ### It works with existing codebase Most libraries require your classes to extend or use decorators from the library itself. This means that types from other libraries or non supported stdlib classes can never be used. It also means that mypy will just work out of the box, rather than requiring plugins. Instead, typedload works fine with the type annotations from the `typing` module and will work without requiring any changes to the datatypes. ### It is easy to extend Since there can be situations that are highly domain specific, typedload allows to extend its functionality to support more types or replace the existing code to handle special cases. ### Support of Union Other libraries tend to either be very [slow](https://pydantic-docs.helpmanual.io/) or just give completely wrong results when Union are involved. Typedload works without having to manually do annoying annotations. # Functional approach You can load a `list[YourType]`, without having to create a loader object or a useless container object. apischema --------- Found [here](https://github.com/wyfo/apischema) It's the only viable alternative to typedload that I've encountered. * Settings are global, a submodule changing a setting will affect the entire application * Type checks are disabled by default * It reuses the same objects in the output, so changing the data might result in subtle bugs if the input data is used again * No native support for attrs (but can be manually added by the user) * No support for PEP 695 pydantic -------- Found [here](https://pydantic-docs.helpmanual.io/) * Complicated API * [The author calls you a liar if your pure python library is faster](https://news.ycombinator.com/item?id=36639943) * [Breaks API all the time, between minor releases.](https://docs.pydantic.dev/latest/changelog/) (43 times in 2 major versions so far) * [They hate](https://github.com/pydantic/pydantic/pull/3264) [benchmarks](https://github.com/pydantic/pydantic/pull/3881) [that show](https://github.com/pydantic/pydantic/pull/1810) [it's slow](https://github.com/pydantic/pydantic/pull/1525). [So they removed them altogether](https://github.com/pydantic/pydantic/pull/3973) * It needs a mypy plugin, and for some kinds of classes it does no static checks whatsoever. * Is now VC funded, so eventually some draconian monetizing plan might appear. #### Version 1 * One of the slowest libraries that exist in this space * `int | float` might decide to cast a `float` to `int`, or an `int` to `float` #### Version 2 * Despite the rewrite in rust, and [taking inspiration from typedload's autotagging of unions](https://github.com/pydantic/pydantic/issues/5163#issuecomment-1619203179) somehow manages to be slower than pure python to load unions. * Took them several years to make a version 2 where types on BaseModel finally mean the same thing that they mean in the rest of python * Took them several years to implement unions that don't cast types at random msgspec ------- * Very fast, but unions don't work * [The author will send you a PR to add his project to the benchmarks](https://github.com/ltworf/typedload/pull/390) [but will refuse to add your project to his benchmarks when you do the same](https://github.com/jcrist/msgspec/pull/333), saying that your project is not popular enough (despite it having many more downloads) In theory unions do work, but you need to refactor your entire project around using msgspec's peculiar idea of unions to use them, and even then they are very limited in scope, compared to what other projects support and python users normally use. * Implemented in C, won't run on PyPy * Supports tagged Unions partially only when inheriting from its Struct type Mypy will not typecheck those classes. To use unions you must give up static typechecking. * Doesn't support unions between regular dataclass/NamedTuple/Attrs/TypedDict * Doesn't support untagged Unions * Doesn't support multiple tags (e.g. `tag=Literal[1, 2]`) * Extended using a single function that must handle all cases * Can't replace type handlers typedload/docs/3.10_load_list_of_ints.svg0000664000175000017500000002413614721335070017714 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 2.5 pydantic2 apischema 2.34 2.35 2.36 load list of ints load list of ints seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/errors.md0000664000175000017500000000557214721335070014700 0ustar salvosalvoErrors in typedload =================== All exceptions are subclasses of `TypedloadException`. To make sure of that, there is an assertion in place that will fail if a type handler is misbehaving and raising the wrong type of exception. The exceptions have a clear user message, but they offer an API to expose precise knowledge of the problem. String trace ------------ By default when an error occurrs the path within the data structure is shown. ```python from typing import * import typedload class Thing(NamedTuple): value: int class Data(NamedTuple): field1: List[Thing] field2: Tuple[Thing, ...] typedload.load({'field1': [{'value': 12}, {'value': 'a'}], 'field2': []}, Data) ``` ```python TypedloadValueError: invalid literal for int() with base 10: 'a' Path: .field1.[1].value ``` The path in the string description tells where the wrong value was found. Trace ----- To be able to locate where in the data an exception happened, `TypedloadException` has the `trace` property, which contains a list `TraceItem`, which help to track where the exception happened. This can be useful to do more clever error handling. For example: ```python try: typedload.load([1, 2, 'a'], List[int]) except Exception as e: print(e.trace[-1]) ``` Will raise an exception and print the last element in the trace ```python TraceItem(value='a', type_=, annotation=Annotation(annotation_type=, value=2)) ``` Another example, with an object: ```python class O(NamedTuple): data: List[int] try: typedload.load({'data': [1, 2, 'a']}, O) except Exception as e: for i in e.trace: print(i) ``` Will print the entire trace: ```python TraceItem(value={'data': [1, 2, 'a']}, type_=, annotation=None) TraceItem(value=[1, 2, 'a'], type_=typing.List[int], annotation=Annotation(annotation_type=, value='data')) TraceItem(value='a', type_=, annotation=Annotation(annotation_type=, value=2)) ``` And checking the `annotation` field it is possible to find out that the issue happened in *data* at index *2*. Union ----- Because it is normal for a union of n types to generate n-1 exceptions, a union which fails generated n exceptions. Typedload has no way of knowing which of those is the important exception that was expected to succeed and instead puts all the exceptions inside the `exception` field of the parent exception. So all the sub exceptions can be investigated to decide which one is the most relevant one. Raise exceptions in custom handlers ----------------------------------- To find the path where the wrong value was found, typedload needs to trace the execution by using annotations. This is used in handlers that do recursive calls to the loader. See the source code of the handlers for Union and NamedTuple to see how this is done. typedload/docs/3.10_load_big_dictionary.svg0000664000175000017500000002637614721335070020216 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 6 7 8 pydantic2 apischema 2.34 2.35 2.36 load big dictionary load big dictionary seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_list_of_NamedTuple_objects.svg0000664000175000017500000002254414721335070022512 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 pydantic2 apischema 2.34 2.35 2.36 load list of NamedTuple objects load list of NamedTuple objects seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_list_of_floats_and_ints.svg0000664000175000017500000002416314721335070022111 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.2 0.4 0.6 0.8 1 pydantic2 apischema 2.34 2.35 2.36 load list of floats and ints load list of floats and ints seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/README.md0000777000175000017500000000000014721335070015775 2../README.mdustar salvosalvotypedload/docs/examples.md0000664000175000017500000003426014721335070015176 0ustar salvosalvoExamples ======== Objects ------- Three different kinds of objects are supported to be loaded and dumped back. * NamedTuple (stdlib) * dataclass (stdlib) * attrs (3rd party module) More or less they all work in the same way: the object is defined, types are assigned for the fields and typedload can inspect the class and create an instance from a dictionary, or go the other way to a dictionary from an instance. ```python from typing import NamedTuple from pathlib import Path import typedload from attr import attrs, attrib class File(NamedTuple): path: Path size: int @attrs class Directory: name = str files: list[File] = attrib(factory=list) # mutable objects require a factory, not a default value dir = { 'name': 'home', 'files': [ {'path': '/asd.txt', 'size': 0}, {'path': '/tmp/test.txt', 'size': 30}, ] } # Load the dictionary into objects d = typedload.load(dir, Directory) # Out: Directory(files=[File(path='/asd.txt', size=0), File(path='/tmp/test.txt', size=30)]) # Dump the objects into a dictionary typedload.dump(d) ``` Loading with optional and default values ---------------------------------------- Python typing is confusing for many concerning the meaning of `Optional`. An `Optional[T]` means that the field can assume `None` as value, but the value must still be specified, and can't be omitted. If, on the other hand, a variable has a default value, then when it's not explicitly specified, the default value is assumed. Typedload follows exactly the normal behaviour of python and mypy. With the new syntax, writing `Optional[int]` is equivalent to `int | None`. ```python import typedload from typing import Optional, NamedTuple class User(NamedTuple): username: str # Must be assigned nickname: Optional[str] # Must be assigned and can be None last_login: Optional[int] = None # Not required. # This fails, as nickname is not present typedload.load({'username': 'ltworf'}, User) # TypedloadValueError: Value does not contain fields: {'nickname'} which are necessary for type User # Those 2 work fine typedload.load({'username': 'ltworf', 'nickname': None}, User) # Out: User(username='ltworf', nickname=None, last_login=None) typedload.load({'username': 'ltworf', 'nickname': 'LtWorf'}, User) # Out: User(username='ltworf', nickname='LtWorf', last_login=None) # Those 2 work fine too typedload.load({'username': 'ltworf', 'nickname': None, 'last_login': None}, User) # Out: User(username='ltworf', nickname=None, last_login=None) typedload.load({'username': 'ltworf', 'nickname': None, 'last_login': 666}, User) # Out: User(username='ltworf', nickname=None, last_login=666) ``` There is of course no relationship between a default value and `Optional`, so a default can be anything. The following is valid: ```python class A(NamedTuple): # The field can be None, but if not specified it defaults to 3 i: Optional[int] = 3 ``` Dumping with optional and default values ---------------------------------------- ```python class Coordinates(NamedTuple): x: int = 0 y: int = 0 ``` When dumping values, the fields which match with their default value are omitted. ```python # Returns an empty dictionary typedload.dump(Coordinates()) # Out: {} # Returns only the x value typedload.dump(Coordinates(x=42, y=0)) # Out: {'x': 42} # To emit all the fields, including those that are using the default one # set hidedefault=False typedload.dump(Coordinates(), hidedefault=False) # Out: {'x': 0, 'y': 0} ``` Tagged unions ------------- A typical case for unions of object is to have a *type* field that type the object itself, in a string. This makes conflicts impossible and so in the union the correct type will always be picked. *This is very fast, because typedload will internally use the `Literal` as an index to find the correct class.* For example, Slack sends events in this way. ```python import typedload from typing import List, Literal, Union, NamedTuple events = [ { "type": "message", "text": "hello" }, { "type": "user-joined", "username": "giufà" } ] # We have events that can be of many types class Message(NamedTuple): type: Literal['message'] text: str class UserJoined(NamedTuple): type: Literal['user-joined'] username: str # Now to load our event list typedload.load(events, List[Union[Message, UserJoined]]) # Out: [Message(type='message', text='hello'), UserJoined(type='user-joined', username='giufà')] ``` As usual, extra fields are ignored by default. If you want to be more strict, enable `failonextra=True`. Untagged unions --------------- Untagged unions are not a very common feature among libraries, but typedload supports them. Of course the problem is that if a value can be loaded into more than one type in the union, the result is not deterministic. For example, using objects where all the fields have a default value is a bad idea: ```python import typedload from typing import NamedTuple, Union, Optional class Person(NamedTuple): name: str = '' class Data(NamedTuple): data: Optional[str] = None # WARNING: This might return either a Person or a Data. It's random typedload.load({}, Union[Person, Data]) # Out: Data(data=None) # Out: Person(name='') ``` To detect the situation, we can use `uniondebugconflict=True` ```python typedload.load({}, Union[Person, Data], uniondebugconflict=True) # Out: TypedloadTypeError: Value of dict could be loaded into Union 2 times ``` This option is intended only for debug, since it will make typedload slower. ### failonextra You might want to use `failonextra` for objects whose fields are subset of other objects. ```python import typedload from typing import NamedTuple, Union class Person(NamedTuple): name: str class Car(NamedTuple): name: str model: str # This should be a Car, not a Person data = {'name': 'macchina', 'model': 'TP21'} # WARNING: This can return either a Person or a Car typedload.load(data, Union[Person, Car]) # Out: Person(name='macchina') # Out: Car(name='macchina', model='TP21') # This can be explained by checking that both of these work typedload.load(data, Person) # Out: Person(name='macchina') typedload.load(data, Car) # Out: Car(name='macchina', model='TP21') # The data we have works for both objects, and the union # picks the first one (python sorts them randomly) # We want to avoid that dictionary to be loaded as Person, so we use failonextra # This fails typedload.load(data, Person, failonextra=True) # TypedloadValueError: Dictionary has unrecognized fields: model and cannot be loaded into Person # This works typedload.load(data, Car, failonextra=True) # Out: Car(name='macchina', model='TP21') # At this point the union will reliably pick the class that we want typedload.load(data, Union[Person, Car], failonextra=True) # Out: Car(name='macchina', model='TP21') ``` Disable cast loading unions --------------------------- Many times it is beneficial to disable casting when loading. For example, if a value can be an object of a certain kind or a string, not disabling casting will cast any invalid object to a string, which might not be desired. ```python import typedload from typing import NamedTuple, Union class Data(NamedTuple): data: int # This loads "{'date': 33}", since the object is not a valid Data object. typedload.load({'date': 33}, Union[str, Data]) # Out: "{'date': 33}" # This fails, because the dictionary is not cast to str typedload.load({'date': 33}, Union[str, Data], basiccast=False) # TypedloadValueError: Value of dict could not be loaded into typing.Union[str, __main__.Data] ``` list[T] | T ----------- Some terribly evil programmers use json in this way: * A list in case they have multiple values * A single object in case they have one value * Nothing at all in case they have zero values Let's see how typedload can help us survive the situation without having to handle all the cases every time. ```python import typedload from typing import NamedTuple, Union, List import dataclasses # Multiple data points, a list is used data0 = { "data_points": [{"x": 1.4, "y": 4.1}, {"x": 5.2, "y": 6.13}] } # A single data point. Instead of a list of 1 element, the element is passed directly data1 = { "data_points": {"x": 1.4, "y": 4.1} } # No data points. Instead of an empty list, the object is empty data2 = {} # Now we make our objects class Point(NamedTuple): x: float y: float @dataclasses.dataclass class Data: # We make an hidden field to load the data_points field from the json # If the value is absent it will default to an empty list # The hidden field can either be a List[Point] or directly a Point object _data_points: Point | list[Point] = dataclasses.field(default_factory=list, metadata={'name': 'data_points'}) @property def data_points(self) -> List[Point]: # We make a property called data_points, that always returns a list if not isinstance(self._data_points, list): return [self._data_points] return self._data_points # Now we can load our data, and they will all be lists of Point typedload.load(data0, Data).data_points # Out: [Point(x=1.4, y=4.1), Point(x=5.2, y=6.13)] typedload.load(data1, Data).data_points # Out: [Point(x=1.4, y=4.1)] typedload.load(data2, Data).data_points # Out: [] ``` Name mangling ------------- Name mangling is primarily used to deal with camel-case in codebases that use snake_case. It is supported using `dataclass` and `attrs`, which provide metadata for the fields. Let's assume that our original data uses camel case. Since we are not maniacs, we want the fields in python to use snake_case, we do the following: ```python from dataclasses import dataclass, field import typedload @dataclass class Character: first_name: str = field(metadata={'name': 'firstName'}) last_name: str = field(metadata={'name': 'lastName'}) data = {"firstName": "Paolino", "lastName": "Paperino"} character = typedload.load(data, Character) # Out: Character(first_name='Paolino', last_name='Paperino') ``` When dumping back the data ```python typedload.dump(character) # Out: {'lastName': 'Paperino', 'firstName': 'Paolino'} ``` the names will be converted back to camel case. Multiple name mangling schemes ------------------------------ If we want to load from a source and dump to another source that uses a different convention, we can use `mangle_key` ```python from dataclasses import dataclass, field import typedload @dataclass class Character: first_name: str = field(metadata={'name': 'firstName', 'alt_name': 'first-name'}) last_name: str = field(metadata={'name': 'lastName', 'alt_name': 'last-name'}) data = {"firstName": "Paolino", "lastName": "Paperino"} character = typedload.load(data, Character) # Out: Character(first_name='Paolino', last_name='Paperino') typedload.dump(character, mangle_key='alt_name') # Out: {'last-name': 'Paperino', 'first-name': 'Paolino'} ``` Load and dump types from str ---------------------------- Some classes are easy to load and dump from `str`. For example this is done for `Path`. Let's assume we want to have a class that is called `SerialNumber` that we load from a string and dump back to a string. Here's how it can be done: ```python from typing import List import typedload.datadumper import typedload.dataloader class SerialNumber: def __init__(self, sn: str) -> None: # Some validation if ' ' in sn: raise Exception('Invalid serial number') self.sn = sn def __str__(self): return self.sn l = typedload.dataloader.Loader() d = typedload.datadumper.Dumper() l.strconstructed.add(SerialNumber) d.strconstructed.add(SerialNumber) serials = l.load(['1', '2', '3'], List[SerialNumber]) d.dump(serials) ``` Custom handlers --------------- Let's assume that our codebase uses methods `from_json()` and `to_json()` as custom methods, and we want to use those. ```python from typing import NamedTuple import typedload.datadumper import typedload.dataloader import typedload.exceptions # This is a NamedTuple, but we want to give priority to the from/to json methods class Point(NamedTuple): x: int y: int @staticmethod def from_json(data): # Checks on the data # Typedload handlers must raise subclasses of TypedloadException to work properly if not isinstance(data, list): raise typedload.exceptions.TypedloadTypeError('List expected') if len(data) != 2: raise typedload.exceptions.TypedloadTypeError('Only 2 items') if not all(isinstance(i, int) for i in data): raise typedload.exceptions.TypedloadValueError('Values must be int') # Return the data return Point(*data) def to_json(self): return [self.x, self.y] # We get a loader l = typedload.dataloader.Loader() # We find which handler handles NamedTuple nt_handler = l.index(Point) # We prepare a new handler load_handler = ( lambda x: hasattr(x, 'from_json'), # Anything that has a from_json lambda loader, value, type_: type_.from_json(value) # Call the from_json and return its value ) # We add the new handler l.handlers.insert(nt_handler, load_handler) # Ready to try it! l.load([1, 2], Point) # Out: Point(x=1, y=2) # Now we do the dumper d = typedload.datadumper.Dumper() nt_handler = d.index(Point(1,2)) # We need to use a real object to find the handler dump_handler = ( lambda x: hasattr(x, 'from_json'), # Anything that has a from_json lambda dumper, value, value_type: value.to_json() # Call the from_json and return its value ) d.handlers.insert(nt_handler, dump_handler) d.dump(Point(5, 5)) # Out: [5, 5] ``` Handlers basically permit doing anything, replacing current handlers or adding more to deal with more types. You can just append them to the list if you are extending. Remember to always use typedload exceptions, implement checks, and never modify the handler list after loading or dumping something. TypedDict with total and required --------------------------------- With TypedDict, when using `total`, it is possible to mix `Required` and `NotRequired` to change the behaviour for one field. ```python class A(TypedDict, total=True): a: int b: int c: NotRequired[int] d: NotRequired[int] class B(TypedDict, total=False): a: Required[int] b: Required[int] c: int d: int ``` typedload/docs/3.10_load_list_of_lists.svg0000664000175000017500000002332214721335070020071 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 pydantic2 apischema 2.34 2.35 2.36 load list of lists load list of lists seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_tagged_union_of_objects.svg0000664000175000017500000002641514721335070021066 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 2.5 3 3.5 4 pydantic2 apischema 2.34 2.35 2.36 tagged union of objects tagged union of objects seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/docs/0000775000175000017500000000000014721335070013761 5ustar salvosalvotypedload/docs/docs/donate.svg0000777000175000017500000000000014721335070020155 2../donate.svgustar salvosalvotypedload/docs/docs/gpl3logo.png0000777000175000017500000000000014721335070020657 2../gpl3logo.pngustar salvosalvotypedload/docs/3.10_load_list_of_floats_and_ints.svg0000664000175000017500000002643214721335070022107 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 2.5 3 3.5 4 pydantic2 apischema 2.34 2.35 2.36 load list of floats and ints load list of floats and ints seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/donate.svg0000664000175000017500000000266114721335065015035 0ustar salvosalvoDonatetypedload/docs/origin_story.md0000664000175000017500000000273014721335070016104 0ustar salvosalvotypedload's origin story ======================== At $DAYJOB there was a software written in Scala, that worked by mapping objects into mongodb data. The only one person there knowing Scala decided to quit, and so we were in the process of rewriting the entire thing in Python. I had been tasked to write a few hundreds methods `to_json()` and `from_json()` for all the various objects that are used by this software. Since I thought it was going to be a terribly boring job in which I'd make tens of typos, I looked for a library that did such a thing. But of course none existed, so I started writing a module to do that. The `to_json()` part was rather easy, while the opposite wasn't, anyway after a few days the module seemed to be working nicely. In fact the module worked so nicely that I wanted to use it in my personal projects as well. However I couldn't, because $DAYJOB owned the copyright, and I knew that getting the authorization to release it as open source would take from 2 years to +∞. So, I just wrote a stand alone library outside of work to do the exact same thing, but in a more generic and flexible way, rather than tied to the specific software we had at $DAYJOB. The result of writing the same library twice was that the second time around it came out better, and so the original version got completely discarded and at $DAYJOB typedload is now in use. At the time pydantic existed but it was not available on any distribution and was not production quality. typedload/docs/CHANGELOG.md0000664000175000017500000002026614721335070014650 0ustar salvosalvo2.37 ==== * Do not use new syntax in any place. It confuses tooling 2.36 ==== * Drop support for EOL versions of python * Support typing.ReadOnly * Add support for typing.TypeAliasType (PEP 695) 2.35 ==== * Add tests to make sure mypy validation works * Fix mypy failure when loading a Literal directly * Remove cloudflare tracking from html documentation once again -_-' Thanks mkdocs for this. * Improve documentation * Improve typechecks 2.34 ==== * Support Required for TypedDict 2.33 ==== * Make example more current * Fix bug with dumping dataclasses with slots 2.32 ==== * Improve performance for loading unions of objects [#12](https://codeberg.org/ltworf/typedload/pulls/12) * Improve performance for dumping dataclasses [#13](https://codeberg.org/ltworf/typedload/pulls/13) [#14](https://codeberg.org/ltworf/typedload/pulls/14) More details on my blog 2.31 ==== * Improve performance for loading various types More details on my blog * Fix bug when loading attrs objects with missing attributes, the correct exception is raised [#9](https://codeberg.org/ltworf/typedload/pulls/9) * Raise TypeError instead of ValueError when there is a problem with the arguments of the objects This is in line with what python does [#9](https://codeberg.org/ltworf/typedload/pulls/9) * Fix bug for dumping object with a ForwardRef to itself [#8](https://codeberg.org/ltworf/typedload/pulls/8) 2.30 ==== * Fix bug where dictionary load would fail if the type for the value wasn't cached already 2.29 ==== * Move project to Codeberg 2.28 ==== * Add support for uuid.UUID 2.27 ==== * Add support for re.Patterns 2.26 ==== * Update type hints file 2.25 ==== * Improve performance for loading objects (attrs/dataclasses/NamedTuple) * Improve performance for loading dictionary keys that are basic types * Improve performance for loading dataclasses * Switch performance tests to test against pydantic2 2.24 ==== * Drop support to Python 3.7 (which has reached EOL) * Make is_optional slightly faster * Keep track of the index when loading iterables the first time It makes the normal case slightly slower, and gives massive performance improvements when exceptions are raised. 2.23 ==== * When loading a string into datetime.date/time/datetime, ISO 8601 is used * When dumping, setting `isodates=True` dumps an ISO 8601 string instead of a list of ints. The previous behaviour is now deprecated. * Add support for datetime.timedelta. It is dumped as a float representing seconds * Deprecate dump handlers without type hints * Improve performance for dumping, by carrying type hints * Remove `jsons` and `dataclasses-json` from benchmarks. They were too slow to be a useful comparison. 2.22 ==== * Improve loading time for literals * Support attrs converter 2.21 ==== * Drop support to Python 3.5 and 3.6 * Improve performance for dumping * Generate pure python wheel 2.20 ==== * Switch to setuptools Since python decided to drop the only installation method available within the stdlib * Add pyproject.toml 2.19 ==== * Fix minor bug about exception raising from string constructed types * Simplify type checking functions, defining only the one for the current python version * Fix type definitions of some private functions for compatibility with cython * Improved loading speed for dictionaries * Improved loading speed for iterators * Improved documentation * Improved performance testing code 2.18 ==== * Fix bug with loading generators that raise exceptions 2.17 ==== * Support for NotRequired * Document performance testing * Improve performances when loading iterables * Greatly improve performances when loading `Union` of objects that are `Literal` annotated 2.16 ==== * Add is_optional function * Support new style union (A | B) * Experimental support for PEP563 `__future__.annotations`. **READ ABOUT DEFERRED EVALUATION IN THE DOCUMENTATION.** 2.15 ==== * Union fails immediately when a non typedload exception is found * New `make html` target to generate the website * Updated CONTRIBUTING file, with details about new licenses from the FSF * Handle typing.NewType 2.14 ==== * Fix bug where AttributeError from name mangling caused an AssertionError 2.13 ==== * Separate and simpler handlers for NamedTuple, dataclass, attrs, TypedDict * Allow duck typing when loading attr (allow any dict-like class to be used) * Minor performance improvements 2.12 ==== * Add `uniondebugconflict` flag to detect unions with conflicts. 2.11 ==== * Make newer mypy happy 2.10 ==== * Fix setup.py referring to a non-existing file when installing with pip 2.9 === * Use README on pypi.org * Tiny speed improvement * Expanded and improved documentation 2.8 === * Better report errors for `Enum` * Improve support for inheritance with mixed totality of `TypedDict` (requires Python 3.9) 2.7 === * failonextra triggers failure when dropping fields in mangling * Support for `total=False` in `TypedDict` * Support `init=False` in `dataclass` field 2.6 === * Handle `Any` types as passthrough * Easy way to handle types loaded from and dumped to `str` * Improve how exceptions are displayed 2.5 === * Fix dump for attr classes with factory * Let name mangling use arbitrary metadata fields rather than just `name` 2.4 === * Support for `ipaddress.IPv4Address`, `ipaddress.IPv6Address`, `ipaddress.IPv4Network`, `ipaddress.IPv6Network`, `ipaddress.IPv4Interface`, `ipaddress.IPv6Interface`. 2.3 === * Better type sorting in `Union` This helps when using `Union[dataclass, str]` 2.2 === * Add Python3.9 to the supported versions * Prevent loading dict as `List`, `Tuple`, `Set` This helps when using `Union[Dict, List]` to take the correct type. 2.1 === * Written new usage example * typechecks internals now pass with more mypy configurations * Fix `import *` 2.0 === * Breaking API change: handlers can only be modified before the first load * Breaking API change: plugins removed (attr support is by default) * Exceptions contain more information * Greatly improve performances with iterables types * Support for `pathlib.Path` 1.20 ==== * Drop support for Python 3.5.2 (3.5 series is still supported) * Support `TypedDict` * More precise type annotation of `TypedloadException` and `Annotation` fields * Deprecate the plugin to handle `attr.s` and make it always supported. This means that there will be no need for special code. * Fix datetime loader raising exceptions with the wrong type 1.19 ==== * Add support for `Literal`. 1.18 ==== * Improved documentation * Debian builds are now done source only 1.17 ==== * Prefer the same type in union loading 1.16 ==== * New `uniontypes()` function. * Make list and dictionary loaders raise the correct exceptions * Able to load from `argparse.Namespace` 1.15 ==== * Add support for `FrozenSet[T]`. * Define `__all__` for typechecks. * Add name mangling support in dataclass, to match attrs. * Add support for `datetime.date`, `datetime.time`, `datetime.datetime` 1.14 ==== * Add support for `Tuple[t, ...]` 1.13 ==== * Fix bug in loading attr classes and passing random crap. Now the proper exception is raised. * New module to expose the internal type checks functions 1.12 ==== * Support fields with factory for dataclass 1.11 ==== * Fixed problem when printing sub-exceptions of failed unions * Improve documentation 1.10 ==== * Make mypy happy again 1.9 === * Support `ForwardRef` * Add a new Exception type with more details on the error (no breaking API changes) 1.8 === * Make mypy happy again 1.7 === * Make mypy happy again 1.6 === * Run tests on older python as well * Support for dataclass (Since python 3.7) * Added methods to find the appropriate handlers 1.5 === * Improve handling of unions * Better continuous integration * Support python 3.7 1.4 === * Add support for name mangling in attr plugin * Parameters can be passed as kwargs * Improved exception message for `NamedTuple` loading 1.3 === * Add support for Python < 3.5.3 1.2 === * Ship the plugins in pypy 1.1 === * Able to load and dump old style `NamedTuple` * Support for Python 3.5 * Target to run mypy in makefile * Refactor to support plugins. The API is still compatible. * Plugin for the attr module, seems useful in Python 3.5 1.0 === * Has a setting to hide default fields or not, in dumps * Better error reporting * Add file for PEP 561 0.9 === * Initial release typedload/docs/3.13_load_list_of_attrs_objects.svg0000664000175000017500000002416314721335070021610 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 -0.1 0 0.1 0.2 0.3 0.4 pydantic2 apischema 2.34 2.35 2.36 load list of attrs objects load list of attrs objects seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_load_list_of_attrs_objects.svg0000664000175000017500000002726114721335070021607 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 -0.1 -0.05 0 0.05 0.1 0.15 0.2 0.25 0.3 0.35 pydantic2 apischema 2.34 2.35 2.36 load list of attrs objects load list of attrs objects seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_load_list_of_NamedTuple_objects.svg0000664000175000017500000002477714721335070022521 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 6 pydantic2 apischema 2.34 2.35 2.36 load list of NamedTuple objects load list of NamedTuple objects seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_tagged_union_of_objects.svg0000664000175000017500000002723614721335070021065 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 pydantic2 apischema 2.34 2.35 2.36 tagged union of objects tagged union of objects seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_load_dictionary_of_tuples.svg0000664000175000017500000002476214721335070021452 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 6 pydantic2 apischema 2.34 2.35 2.36 load dictionary of tuples load dictionary of tuples seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/version_numbers.md0000664000175000017500000000074214721335070016576 0ustar salvosalvoVersion numbers =============== Breaking API changes happen when the first number increases. So far they have been minimal. The second number being bumped means bugs were fixed or new features introduced, but the API remained compatible. Dropping support for EOL python versions is not considered breaking API. Changes that trigger failures in buggy code are acceptable [See here](https://lwn.net/Articles/416821/). I am not Linus Torvalds and I don't have to follow his rules. typedload/docs/3.13_load_list_of_dataclass_objects.svg0000664000175000017500000002562514721335070022416 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.2 0.4 0.6 0.8 1 1.2 1.4 pydantic2 apischema 2.34 2.35 2.36 load list of dataclass objects load list of dataclass objects seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_dump_objects.svg0000664000175000017500000002556114721335070016705 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.2 0.4 0.6 0.8 1 1.2 1.4 pydantic2 apischema 2.34 2.35 2.36 dump objects dump objects seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_fail_load_list_of_floats_and_ints.svg0000664000175000017500000002501714721335070023100 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 2.5 3 pydantic2 apischema 2.34 2.35 2.36 fail load list of floats and ints fail load list of floats and ints seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_dictionary_of_tuples.svg0000664000175000017500000002560214721335070021447 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 2.5 3 3.5 pydantic2 apischema 2.34 2.35 2.36 load dictionary of tuples load dictionary of tuples seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_load_list_of_dataclass_objects.svg0000664000175000017500000002416014721335070022404 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 pydantic2 apischema 2.34 2.35 2.36 load list of dataclass objects load list of dataclass objects seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_list_of_ints.svg0000664000175000017500000002557314721335070017725 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 -0.1 0 0.1 0.2 0.3 0.4 0.5 0.6 pydantic2 apischema 2.34 2.35 2.36 load list of ints load list of ints seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.10_load_with_alias.svg0000664000175000017500000002413014721335070017336 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 -0.1 -0.08 -0.06 -0.04 -0.02 0 pydantic2 apischema 2.34 2.35 2.36 load with alias load with alias seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_with_alias.svg0000664000175000017500000002475114721335070017352 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 -0.1 0 0.1 0.2 0.3 0.4 0.5 pydantic2 apischema 2.34 2.35 2.36 load with alias load with alias seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/CONTRIBUTING.md0000664000175000017500000000255214721335070015266 0ustar salvosalvoContributing ============ All contributions must pass the test suite and must generate no warnings with the latest available version of mypy. The best way of sending changes is to use git-send-mail to tiposchi@tiscali.it It is acceptable also to use codeberg's pull request functionality. Contributors must accept that their changes can use both GPL3 and LGPL3. Currently the license is GPL3 with one exception being made for the company where I work. In the future more LGPL3 exception could be made, but no other license than those will be used. In the event that new versions of GPL and LGPL licenses should be published by the Free Software Foundation (FSF) in the future, contributors must accept that their contribution might be licensed with those future versions of GPL and LGPL in addition to the current version. This will be decided by the owners of the project if and when new versions of the licenses are created and is not automatic, to prevent the case where a new board of the FSF should decide to abandon its mission and grant less freedom to the users. For new versions that aim at fixing corner cases (such as version 3), they will be used and the software will be available under multiple licenses versions (starting from 3). They will not be adopted should the FSF decide that GPL4 should be a non-copyleft license or other similar spirit altering changes. typedload/docs/3.10_fail_tagged_union_of_objects.svg0000664000175000017500000002415414721335070022054 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 pydantic2 apischema 2.34 2.35 2.36 fail tagged union of objects fail tagged union of objects seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/SECURITY.md0000664000175000017500000000044714721335070014627 0ustar salvosalvo# Security Policy I do not expect any security issues in this package. ## Supported Versions Only the latest release is supported. I will not backport fixes. ## Reporting a Vulnerability Contact me at tiposchi@tiscali.it My PGP key is on this file, on git. debian/upstream/signing-key.asc typedload/docs/supported_types.md0000664000175000017500000003302414721335070016626 0ustar salvosalvoSupported types =============== None ---- ```python typedload.load(obj, None) ``` It will either return a None or fail. This is normally used to handle unions such as `Optional[int]` rather than by itself. Basic types ----------- By default: `{int, bool, float, str, NONETYPE}` Those types are the basic building blocks and no operations are performed on them. *NOTE*: If `basiccast=True` (the default) casting between them can still happen. ```python In : typedload.load(1, float) Out: 1.0 In : typedload.load(1, str) Out: '1' In : typedload.load(1, int) Out: 1 In : typedload.load(1, float, basiccast=False) Exception: TypedloadValueError In : typedload.load(1, bool, basiccast=False) Exception: TypedloadValueError ``` The `basictypes` set can be tweaked. ```python In : typedload.load(1, bytes, basictypes={bytes, int}) Out: b'\x00' In : typedload.load(1, int, basictypes={bytes, int}) Out: 1 ``` typing.Literal -------------- ```python typedload.load(obj, Literal[1]) typedload.load(obj, Literal[1,2,3]) ``` Succeeds only if obj equals one of the allowed values. This is normally used in objects, to decide the correct type in a `Union`. It is very common to use Literal to disambiguate objects in a Union. [See example](examples.md#object-type-in-value) *This is very fast, because typedload will internally use the `Literal` values to try the best type in the union first.* enum.Enum --------- ```python class Flags(Enum): NOVAL = 0 YESVAL = 1 In : typedload.load(1, Flags) Out: ``` Load values from an Enum, when dumping the value is used. list ---- ```python In : typedload.load([1, 2, 3], list[int]) Out: [1, 2, 3] In : typedload.load([1.1, 2, '3'], list[int]) Out: [1, 2, 3] In : typedload.load([1.1, 2, '3'], list[int], basiccast=False) Exception: TypedloadValueError ``` Load an iterable into a list object. Always dumped as a list. tuple ----- Always dumped as a list. ### Finite size tuple ```python In : typedload.load([1, 2, 3], tuple[int, float]) Out: (1, 2.0) # Be more strict and fail if there is more data than expected on the iterator In : typedload.load([1, 2, 3], tuple[int, float], failonextra=True) Exception: TypedloadValueError ``` ### Infinite size tuple ```python In : typedload.load([1, 2, 3], tuple[int, ...]) Out: (1, 2, 3) ``` Uses Ellipsis (`...`) to indicate that the tuple contains an indefinite amount of items of the same size. dict ---- ```python In : typedload.load({1: '1'}, dict[int, Path]) Out: {1: PosixPath('1')} In : typedload.load({1: '1'}, dict[int, str]) Out: {1: '1'} In : typedload.load({'1': '1'}, dict[int, str]) Out: {1: '1'} In : typedload.load({'1': '1'}, dict[int, str], basiccast=False) Exception: TypedloadValueError class A(NamedTuple): y: str='a' In : typedload.load({1: {}}, dict[int, A], basiccast=False) Out: {1: A(y='2')} ``` Loads a dictionary, making sure that the types are correct. Objects ------- * typing.NamedTuple * dataclasses.dataclass * attr.s ```python class Point2d(NamedTuple): x: float y: float class Point3d(NamedTuple): x: float y: float z: float @attr.s class Polygon: vertex: list[Point2d] = attr.ib(factory=list, metadata={'name': 'Vertex'}) @dataclass class Solid: vertex: list[Point3d] = field(default_factory=list) total: int = field(init=False) def __post_init__(self): self.total = 123 # calculation here In : typedload.load({'Vertex':[{'x': 1,'y': 1}, {'x': 2,'y': 2},{'x': 3,'y': 3}]}, Polygon) Out: Polygon(vertex=[Point2d(x=1.0, y=1.0), Point2d(x=2.0, y=2.0), Point2d(x=3.0, y=3.0)]) In : typedload.load({'vertex':[{'x': 1,'y': 1,'z': 1}, {'x': 2,'y': 2, 'z': 2},{'x': 3,'y': 3,'z': 3}]}, Solid) Out: Solid(vertex=[Point3d(x=1.0, y=1.0, z=1.0), Point3d(x=2.0, y=2.0, z=2.0), Point3d(x=3.0, y=3.0, z=3.0)], total=123) ``` They are loaded from dictionaries into those objects. `failonextra` when set can generate exceptions if more fields than expected are present. When dumping they go back to dictionaries. `hide_default` defaults to True, so all fields that were equal to the default will not be dumped. ### attrs converters Attrs fields can have a converter function associated. If this is the case, typedload will ignore the assigned type, inspect the type hints of the converter function, and assign the type of the parameter of the converter as type. If the function is not typed, `Any` will be used. This can be useful when the data format has been changed in a more complex way than just adding a few extra fields. Then the converter function can be used to do the necessary conversions for the old data format. #### Examples ```python @attr.s class A: x: int = attr.ib(converter=str) # x has a converter that just calls str() In : load({'x': [1]}, A) Out: A(x='[1]') # In this case the int type for x was completely ignored, because a converter is defined # The str() function does not define type hints, so Any is used # So the list [1] is passed as is to the constructor of A() which calls str() on it to convert it ``` ```python @attr.s class Old: oldfield: int = attr.ib() @attr.s class New: newfield: int = attr.ib() def conv(p: Old | New) -> New: # The type hinting necessary to tell typedload what to do # Without hinting it would just pass the dictionary directly if isinstance(p, New): return p return New(p.oldfield) @attr.s class Outer: ''' Our old data format was using the Old class, but we now use the New class. The converter returns a New instance from an Old instance. ''' inner: New = attr.ib(converter=conv) # Calling load with the new data format, returns a New class In : load({'inner': {'newfield':3}}, Outer) Out: Outer(inner=New(newfield=3)) # Loading with the old data format, still returns a New class In : load({'inner': {'oldfield':3}}, Outer) Out: Outer(inner=New(newfield=3)) ``` Forward references ------------------ A forward reference is when a type is specified as a string instead of as an object: ```python a: ObjA = ObjA() a: 'ObjA' = ObjA() ``` The 2nd generates a forward reference, that is, a fake type that is really hard to resolve. The current strategy for typedload is to cache all the names of the types it encounters and use this cache to resolve the names. In alternative, it is possible to use the `frefs` dictionary to manually force resolution for a particular type. Python `typing` module offers some ways to resolve those types which are not used at the moment because they are slow and have strong limitations. Python developers want to turn every type annotation into a forward reference, for speed reasons. This was supposed to come in 3.10 but has been postponed. So for the moment there is little point into working on this very volatile API. typing.Union ------------ A union means that a value can be of more than one type. If the passed value is of a `basictype` that is also present in the Union, the value will be returned. Otherwise, basictype values are evaluated last. This is to avoid that a Union containing a `str` will catch more than it should. ```python3 typedload.load(data, int | str) ``` ### Tagged unions If all the types within the union have a field of Literal type, that will be used to quickly inspect the value and decide which type to use. Unlike other libraries, no manual action needs to be taken, besides having the fields with the Literal type in each member of the union. ```python3 @dataclass class A: type: Literal['A'] ... @dataclass class B: type: Literal['B'] ... # It will inspect the data and try the correct type directly typedload.load(data, A | B) ``` ### Optional A typical case is when using Optional values ```python In : typedload.load(3, Optional[int]) Out: 3 In : typedload.load(None, Optional[int]) Out: None ``` ### Ambiguity Ambiguity can sometimes be fixed by enabling `failonextra` or disabling `basiccast`. ```python Point2d = tuple[float, float] Point3d = tuple[float, float, float] # This is not what we wanted, the 3rd coordinate is lost In : typedload.load((1,1,1), Union[Point2d, Point3d]) Out: (1.0, 1.0) # Make the loading more strict! In : typedload.load((1,1,1), Union[Point2d, Point3d], failonextra=True) Out: (1.0, 1.0, 1.0) ``` But in some cases it cannot be simply solved, when the types in the Union are too similar. In this case the only solution is to rework the codebase. ```python # A casting must be done, str was chosen, but could have been int In : typedload.load(1.1, Union[str, int]) Out: '1.1' class A(NamedTuple): x: int=1 class B(NamedTuple): y: str='a' # Both A and B accept an empty constructor In : typedload.load({}, Union[A, B]) Out: A(x=1) ``` #### Finding ambiguity Typedload can't solve certain ambiguities, but setting `uniondebugconflict=True` will help detect them. ```python In : typedload.load({}, Union[A, B], uniondebugconflict=True) TypedloadTypeError: Value of dict could be loaded into typing.Union[__main__.A, __main__.B] multiple times ``` So this setting can be used to find ambiguities and manually correct them. *NOTE*: The setting slows down the loading of unions, so it is recommended to use it only during tests or when designing the data structures, but not in production. typing.TypedDict ---------------- ```python class A(TypedDict): val: str In : typedload.load({'val': 3}, A) Out: {'val': '3'} In : typedload.load({'val': 3,'aaa':2}, A) Out: {'val': '3'} In : typedload.load({'val': 3,'aaa':2}, A, failonextra=True) Exception: TypedloadValueError ``` From dict to dict, but it makes sure that the types are as expected. It also supports non-total TypedDict. ```python class A(TypedDict, total=False): val: str In : typedload.load({}, A) Out: {} ``` ### Required/NotRequired **Required** and **NotRequired** can also be used. ```python class A(TypedDict): val: str vol: NotRequired[int] In : typedload.load({'val': 'a'}, A) Out: {'val': 'a'} ``` ```python class A(TypedDict, total=False): val: str vol: Required[int] In : typedload.load({'val': 'a', 'vol': 1}, A) Out: {'val': 'a', 'vol': 1} ``` ### ReadOnly ReadOnly can be used, the effect is that the inner type gets used to typechecking and it is otherwise ignored. set, frozenset -------------- ```python In : typedload.load([1, 4, 99], set[float]) Out: {1.0, 4.0, 99.0} In : typedload.load(range(12), set[int]) Out: {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11} In : typedload.load(range(12), frozenset[float]) Out: frozenset({0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0}) ``` Loads an iterable inside a `set` or a `frozenset`. Always dumped as a list. typing.Any ---------- ```python typedload.load(obj, typing.Any) ``` This will just return `obj` without doing any check or transformation. To work with `dump()`, `obj` needs to be of a supported type, or an handler is needed. typing.NewType -------------- ```python T = typing.NewType('T', str) typedload.load('ciao', T) ``` Allows the use of NewType to define already handled types. typing.TypeAliasType -------------------- This was instroduced with *PEP 695: Type Parameter Syntax*, and is available since python 3.12. in typedload it is possible to do this ```python type number = int | float typedload.load(3, number) ``` It is possible to use TypeAliasType as types of fields: ```python type number = int | float class A(NamedTuple): i: number typedload.load({'i': 3}, A) ``` ### attr The feature works with attr if regular type annotations are used. But at this point converter functions using type aliases are not supported. ### Generics The generics are not supported, because typedload needs an actual type to use, so `type Point[T] = tuple[T, T]` will not work. This is not a bug. ### Maturity This feature is very new. There are test cases but since it hasn't been used in production yet, there might be missing features or issues. String constructed ------------------ Loaders and dumpers have a set of `strconstructed`. Those are types that accept a single `str` parameter in their constructor and have a `__str__` method that returns that parameter. It is possible to add more by adding them to the `strconstructed` set. The preset ones are: ### pathlib.Path ```python In : typedload.load('/tmp/', Path) Out: PosixPath('/tmp') In : typedload.load('/tmp/file.txt', Path) Out: PosixPath('/tmp/file.txt') ``` Loads a string as a `Path`; dumps it as a string. ### ipaddress.IPv*Address/Network/Interface * `ipaddress.IPv4Address` * `ipaddress.IPv6Address` * `ipaddress.IPv4Network` * `ipaddress.IPv6Network` * `ipaddress.IPv4Interface` * `ipaddress.IPv6Interface` ```python In : typedload.load('10.1.1.3', IPv4Address) Out: IPv4Address('10.1.1.3') ``` Loads a string as an one of those classes, and dumps as a string. ### uuid.UUID * `uuid.UUID` Loads a string as `UUID`; dumps it as a string. argparse.Namespace ------------------ This is converted to a dictionary and can be loaded into NamedTuple/dataclass. Dates ----- ### `datetime.timedelta` Represented as a float of seconds. ### `datetime.date` `datetime.time` `datetime.datetime` When loading, it is possible to pass a string in ISO 8601, or a list of ints that will be passed to the constructor. When dumping, the default is to dump a list of ints, unless `isodates=True` is set in the dumper object, in which case an ISO 8601 string will be returned instead. The format with the list of ints is deprecated and kept for backward compatibility. Everybody should use the ISO 8601 strings. The format with the list of ints does not support timezones. re.Pattern ---------- Loads a str or bytes as a compiled Pattern object by passing through re.compile. When dumping gives back the original str or bytes pattern. typedload/docs/gpl3logo.png0000664000175000017500000001473014721335065015276 0ustar salvosalvoPNG  IHDRDZ}bKGD pHYs B(xtIMEQseIDATxyTՙU(F-"ƅ>K&.-f5qщF8:3Q$$&ƠE +,QiSoujSշz{snmI;]=~@W ,^;X?Wnbl@988J>9 #~f*]o [d@-A'Ig,P78qXMy[}/f9x}?AumVxfzo Tm`)N Q8$) TgVW~(fvO'ˇy3HLŐN4( aVǀO6M6>*[gR yx=2}x:O,lr_9ϴQd`upmjFŶ-_v.rӐ9o@g}`cm>mp۴ # * <5 c|P9;( 9K@..rB=W_) >8J+00l C&{rrSr#;X1Ecc3i \z 7pk2HcNJSW#j34 ׅd#<z%IGD`LM;A9h۞ze;1C @} 0uT3|%vz?t%"0/,_}G cqF);:fп-y9d Җ2|I-<(R=S7 `80_83fl&50&v9%^y o8P*))>_%V|4Zebַ!8(uʘ1pkjZZ,8Սp2g) kwBe!䔧 }}w=t)95v\Wqi),TNjV0V ,bœSP,E7ۥVqL{C[b' ŵQJ'tb6 ߉Hscc(?c {pXH?_U8JMRH&=ŀWѵXe.Ro8 GC|bʌ#hgbˎJp̑:k /LE͊\q%Qj3> 髯2^ sUڄ4Y;.ȓ1E.=JprVu)?)si p4Q8&oJ{jp:V!3$8M;sP<\҂UcxP`xb;DJm1P($j_Mܿ\Yyːn h#A#NwmiTNh8%+{&8~k;<U\sR6k`SzƜ4m`ß5!iE]qꅐi8Np|!0L7v/.\vv(ݑ(`@b~M(l餈⩘SK3$Lt/ L;x່ʊ(/-t5 )bt1'0.,QziBtRc4H3;F:QdWOJ!p1e88uI;"D]KKy5S716%Vhc2GpS|Sݾ™l:|,kc*^AvLsjB!1}3ؾPa-$sc|&F38x\'?N*i3ey&zǼ)32n2B& Z.(.%+cNM-ב( WyUXzQ A2i1e8a_CF<ҝNZ\;ƩO ž<^y q6&_I< 37UYٟ/nBp܉MX\J$&Ȭi)Bl#V,YK̹bwU(J,u8xOcE`т"biB%/!q6 ;LMDuWK?;X׀4rOct30$cN5:sXwj@׹˗-_Q4a8cs_"lMUR2sD5:vC fZ&9,|ʦ Ѳ%0erg`\^7q5Yy(}!3%x-kUB^&[Jȯ|Q믈uh*اk$G*mCv4-,&FNj`}/;`,29\Lh  lC3W]"n;+uհ)ZoKH85ċf.u6S )v򧆉g]$}joBOMz6ݺ[.v&Aݪo*^΋ؒ\QClTx2^7v)کws}AS6_QTcrPqA-i&z ״(By3jdl8ǟߘ +j&[ +XK7j(\A+αKƒL $e,{_i T["8|2MyKzngL$gi"1\㲀&mN  M,M\&6,EIۘTVHmF9[Ҏ- f.2EXo2e/,kòa"FɤՍ]< \ĮG[ccfظ$re7:<=2"^XV{` m.Xugi>-/TegO]H K:U+qU:4/p y1ƞ6`bm{\^Vltj<';)#`gñ!aʼn~YBnEM(I r0 O`<תi\L8e=Q/Gb}V>  ` ^CXfP["(E@א7-pXkC`^|n&_z(gHq/V}K.ƪX۪|A`\òqz]%X?SMXk®e`Fp6K>{*be3ܫj+V4kPQ0y3_2yw;xR[3/ A_g kWܯ}iG!{8*k6ՁkTN4ic_EvMKL=<9SY'I_*\ '[Xվ^gi,7/YUhS1r@D_\udT_jEmpIޠmy%I;͘뇹H|}1-F^޻mPyFG#^ u=?~0[f?i2_J"vmBB3%D<9{sVzV>ATK,Rۿ{Boe K}U;* *6 ܳ.HI8X|tЍHF|*&gs4G&&^=|"]97 ̹^Gc ~'aSåQi*7IgܿH6x+^V^liչT;zE>}!nX$D :LSO,ҦVFfԈk]~KsWH<='*}4N'bM&3XϱԫpMz6A{T[:C~b SU gǛD(PPds3Հ/9*y2%l0>W y/s߈e8['pPu:̈́{"\mY 6()Dk죰us>+|wGi|}&цy.hY1>q9]NxNzoa6. z9al-?W* E-Ђ8ccrf?(RI>$ʹbVV?ixq)!<S*PIENDB`typedload/docs/performance.md0000664000175000017500000000356214721335070015662 0ustar salvosalvoPerformance =========== Negative values mean that the library failed the test. The tests are done on my PC. The following libraries are tested: * `typedload`, the 3 most recent versions. It shines with tagged unions, which is what I mostly use. * `pydantic2` years of work to rewrite it in Rust, [implemented detection of tagged unions years after I did it](https://github.com/pydantic/pydantic/issues/5163#issuecomment-1619203179), still managing to lose some benchmarks 😅 * `apischema` is slower where there are unions, faster otherwise Using Python 3.13 ----------------- ![performance chart](3.13_tagged_union_of_objects.svg "Load tagged union of objects") ![performance chart](3.13_dump_objects.svg "Dump objects") ![performance chart](3.13_load_list_of_floats_and_ints.svg "Load list of floats and ints") ![performance chart](3.13_load_list_of_lists.svg "Load list of lists") ![performance chart](3.13_load_list_of_NamedTuple_objects.svg "Load list of NamedTuple") ![performance chart](3.13_load_big_dictionary.svg "Load big dictionary") ![performance chart](3.13_load_list_of_ints.svg "Load list of ints") Using Pypy 7.3.17 ----------------- ![performance chart](3.10_tagged_union_of_objects.svg "Load tagged union of objects") ![performance chart](3.10_dump_objects.svg "Dump objects") ![performance chart](3.10_load_list_of_floats_and_ints.svg "Load list of floats and ints") ![performance chart](3.10_load_list_of_lists.svg "Load list of lists") ![performance chart](3.10_load_list_of_NamedTuple_objects.svg "Load list of NamedTuple") ![performance chart](3.10_load_big_dictionary.svg "Load big dictionary") ![performance chart](3.10_load_list_of_ints.svg "Load list of ints") Run the tests ------------- Generate the performance chart locally. ```bash python3 -m venv perfvenv . perfvenv/bin/activate pip install apischema pydantic attrs export PYTHONPATH=$(pwd) make gnuplot ``` typedload/docs/3.10_load_list_of_large_NamedTuples.svg0000664000175000017500000002501214721335070022324 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 -0.1 0 0.1 0.2 0.3 0.4 0.5 pydantic2 apischema 2.34 2.35 2.36 load list of large NamedTuples load list of large NamedTuples seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_big_dictionary.svg0000664000175000017500000002412714721335070020211 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 pydantic2 apischema 2.34 2.35 2.36 load big dictionary load big dictionary seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/CODE_OF_CONDUCT.md0000664000175000017500000000634614721335070015641 0ustar salvosalvoInternational code of conduct ============================= No USA cultural imperialism allowed ----------------------------------- This project welcomes every contributor from any background. For this reason we can't let the USA and USA influenced politically correct culture dictate conduct for everyone. Diversity is beautiful, let's not ask of people to forgo their culture to contribute. Achieving social justice is important. Being superficial about it only to feel morally superior is not the way to achieve it and is not tolerated here. The code of conduct only pertains this project ---------------------------------------------- This document only applies to the project and the communication channels. It does not apply to anything any contributor might say or do outside of project channels. It only applies to contributors. People whose only contribution is a code of conduct complaint are not contributors. Language -------- Try to be nice and constructive. Harassing and intentionally offending other people is not allowed. Foul language is allowed. People often contribute to this project in their own time and are not paid, for this reason asking contributors to behave "professionally" makes no sense. Hobbies do not require professionality. Jokes are allowed. It can happen to unintentionally offend someone. Do not reiterate the offensive behaviour, provided that the request is reasonable. People who are easily offended by things not intended to be offensive must try to become more tolerant towards other people, other cultures and their ways of expressing themselves. For example, a person might consider offensive the sight of a woman with or without a headscarf. This person needs to try to become more tolerant to other people's culture. It is not allowed to be offended on behalf of others. Please do not presume to know what others are thinking. Examples of allowed language: * This software is retarded * This program runs like shit * This bug is annoying Examples of disallowed language: * You are retarded * You are shitty and so is your program Skill discrimination is absolutely fine --------------------------------------- Unlike other code of conducts, this allows skill discrimination. Everyone is welcome to contribute according to their skill level and more experienced contributors are encouraged to act as mentors. It is nice if they have time and patience to mentor potential contributors, but since time is a limited resource, it is also fine to turn down low quality and low effort contributions with little explaination. New contributors are expected to respond to comments and be willing to improve the quality of their contribution. Conflict resolution ------------------- This code of conduct is inevitably vague. Follow the intention rather than the letter. The final word rests with the project owners or their delegates. Changes to license ------------------ It is not allowed to ask for license change and complain about copyleft. If you disagree with the license, feel free to start your own project from scratch without getting in touch and never look at the source code, to avoid copyright issues. See also -------- * [International code of conduct](https://codeberg.org/ltworf/international_code_of_conduct) typedload/docs/deferred_evaluation.md0000664000175000017500000000210014721335070017353 0ustar salvosalvoDeferred evaluation =================== [PEP 563](https://peps.python.org/pep-0563/) defines deferred evaluation of types. It will most likely be superseeded by [PEP 649](https://peps.python.org/pep-0649/) because of the following issues: * `eval()` is slow * `eval()` might not be present to save space * only works for types defined at module level It is enabled with `from __future__ import annotations`. When it is enabled you must set `pep563=True` in your loader object, to (hopefully) make it keep working (it will not work in many corner cases). ```python from __future__ import annotations class A(NamedTuple): a: Optional[int] load({'a':1}, A) # TypedloadValueError: ForwardRef 'Optional[int]' unknown load({'a':1}, A, pep563=True) # A(a=1) ``` If you have such a simple case it will work fine. In more complicated cases it will not work. In those cases the solution is to not do the import. This feature will most likely be removed once the decision for the newer PEP is settled. It is not part of Python and you should not expect that typedload will keep it. typedload/docs/3.10_dump_objects.svg0000664000175000017500000002411414721335070016673 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 5 pydantic2 apischema 2.34 2.35 2.36 dump objects dump objects seconds x-units typedload performance test python 3.10.14 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_list_of_lists.svg0000664000175000017500000002332114721335070020073 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.5 1 1.5 2 pydantic2 apischema 2.34 2.35 2.36 load list of lists load list of lists seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_fail_load_list_of_floats_and_ints.svg0000664000175000017500000002417514721335070023107 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.2 0.4 0.6 0.8 1 pydantic2 apischema 2.34 2.35 2.36 fail load list of floats and ints fail load list of floats and ints seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_fail_tagged_union_of_objects.svg0000664000175000017500000002334214721335070022055 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 1 2 3 4 pydantic2 apischema 2.34 2.35 2.36 fail tagged union of objects fail tagged union of objects seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docs/3.13_load_list_of_large_NamedTuples.svg0000664000175000017500000002500714721335070022333 0ustar salvosalvo Gnuplot Produced by GNUPLOT 6.0 patchlevel 0 0 0.2 0.4 0.6 0.8 1 1.2 pydantic2 apischema 2.34 2.35 2.36 load list of large NamedTuples load list of large NamedTuples seconds x-units typedload performance test python 3.13.0 Intel(R) Xeon(R) CPU E3-1246 v3 3.50GHz typedload/docgen0000775000175000017500000000166014721335070013271 0ustar salvosalvo#!/usr/bin/python3 import sys import os pname = sys.argv[1] fname = os.path.basename(pname).replace('_docgen.md', '') with open(pname, 'wt') as f: locals= {} exec(f''' import {fname} doc = {fname}.__doc__ functions = [] classes = [] for name in getattr({fname}, '__all__', []): try: item = getattr({fname}, name) except Exception: continue if " copyright: Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli theme: readthedocs use_directory_urls: false nav: - Home: README.md #- Origin story: origin_story.md - Changelog: CHANGELOG.md - Using typedload: - Examples: examples.md - Supported types: supported_types.md - Errors: errors.md - Deferred evaluation of types: deferred_evaluation.md - Docstrings: - typedload: typedload_docgen.md - typedload.dataloader: typedload.dataloader_docgen.md - typedload.datadumper: typedload.datadumper_docgen.md - typedload.typechecks: typedload.typechecks_docgen.md - typedload.exceptions: typedload.exceptions_docgen.md - Comparisons: - Why typedload: comparisons.md - Performance: performance.md - Contributors: - Contributing: CONTRIBUTING.md - Code of conduct: CODE_OF_CONDUCT.md - Links: - Git: https://codeberg.org/ltworf/typedload/ - Downloads: https://codeberg.org/ltworf/typedload/releases - Bug reports: https://codeberg.org/ltworf/typedload/issues - Donate: https://liberapay.com/ltworf - Debian package: https://packages.debian.org/search?keywords=python3-typedload - Pypi package: https://pypi.org/project/typedload/ - Other: - Versioning scheme: version_numbers.md typedload/LICENSE0000664000175000017500000012436014721335070013114 0ustar salvosalvoThis software is released under the GNU General Public License 3. An exception to this is granted to Appgate Cybersecurity, Inc., which is allowed to use this software under the GNU Lesser General Public License 3. Because the author works there. Verbatim text of GNU GPL 3 and GNU LGPL 3 follows. ===================================================================== GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ============================================================================ GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. typedload/CONTRIBUTING.md0000777000175000017500000000000014721335070017506 2docs/CONTRIBUTING.mdustar salvosalvotypedload/CHANGELOG0000777000175000017500000000000014721335070016047 2docs/CHANGELOG.mdustar salvosalvotypedload/README.md0000664000175000017500000000761514721335070013371 0ustar salvosalvotypedload ========= 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) typedload/example.py0000775000175000017500000000745114721335070014120 0ustar salvosalvo#!/usr/bin/python3 # typedload # Copyright (C) 2020-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli # This is a practical example on how to use the typedload library. # It is a somewhat simple use case so most capabilities are not # shown here. # Json data is downloaded from the internet and then loaded into # Python data structures (dictionaries, lists, strings, and so on). #This example queries github API import argparse from datetime import datetime from uuid import UUID import json from typing import * import urllib.request import typedload class CommandLine(NamedTuple): full: bool project: Optional[str] username: Optional[str] def get_url(self) -> str: if self.username is None and self.project is None: username = 'ltworf' project = 'relational' elif self.username and self.project: username = self.username project = self.project else: raise ValueError('Username and project need to be set together') return f'https://codeberg.org/api/v1/repos/{username}/{project}/releases' class User(NamedTuple): id: int login: str email: str created: datetime username: str class Asset(NamedTuple): id: int name: str size: int download_count: int created_at: datetime uuid: UUID browser_download_url: str class Release(NamedTuple): id: int tag_name: str name: str url: str html_url: str tarball_url: str zipball_url: str draft: bool prerelease: bool created_at: datetime published_at: datetime author: User assets: List[Asset] def get_data(args: CommandLine) -> Any: """ Use the github API to get releases information """ req = urllib.request.Request(args.get_url()) with urllib.request.urlopen(req) as f: return json.load(f) def print_report(data: List[Release], args: CommandLine): for i in data: if i.draft or i.prerelease: continue print('Release:', i.name, end=' ') if args.full: print('Created by:', i.author.login, 'on:', i.created_at) else: print() for asset in i.assets: if asset.download_count or args.full: print('\t%d\t%s' % (asset.download_count, asset.name)) def main(): parser = argparse.ArgumentParser() parser.add_argument('-u', '--username', help='The username to query') parser.add_argument('-p', '--project', help='The project to query') parser.add_argument('-f', '--full', help='Print the full report', action='store_true') # We load the args into a NamedTuple, so it is no longer an obscure dynamic object but it is typed args = typedload.load(parser.parse_args(), CommandLine) data = get_data(args) # Github returns dates like this "2016-08-23T18:26:00Z", which are not supported by typedload # So we make a custom handler for them. loader = typedload.dataloader.Loader() # We know what the API returns so we can load the json into typed data typed_data = loader.load(data, List[Release]) print_report(typed_data, args) if __name__ == '__main__': main() typedload/mypy.conf0000664000175000017500000000020114721335070013737 0ustar salvosalvo[mypy] #warn_unused_ignores=True warn_redundant_casts=True strict_optional=True scripts_are_modules=True check_untyped_defs=True typedload/pyproject.toml0000664000175000017500000000174614721335137015031 0ustar salvosalvo[project] name = "typedload" version = "2.37" authors = [ { name="Salvo 'LtWorf' Tomaselli", email="tiposchi@tiscali.it" }, ] description = "Load and dump data from json-like format into typed data structures" readme = "README.md" requires-python = ">=3.9" classifiers = ['Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Typing :: Typed', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3.10', 'Programming Language :: Python :: 3.11', 'Programming Language :: Python :: 3.12', 'Programming Language :: Python :: 3.13'] keywords = ['typing', 'types', 'mypy', 'json', 'schema', 'json-schema', 'python3', 'namedtuple', 'enums', 'dataclass', 'pydantic'] license = {file = "LICENSE"} [project.urls] "Homepage" = "https://ltworf.codeberg.page/typedload/" "Bug Tracker" = "https://codeberg.org/ltworf/typedload/issues" [build-system] requires = ["setuptools", "wheel"] typedload/typedload/0000775000175000017500000000000014721335100014060 5ustar salvosalvotypedload/typedload/exceptions.py0000664000175000017500000001250514721335070016624 0ustar salvosalvo""" typedload Exceptions """ # Copyright (C) 2018-2021 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from enum import Enum from typing import Any, List, NamedTuple, Optional, Type, Union __all__ = [ 'TypedloadException', 'TypedloadValueError', 'TypedloadTypeError', 'TypedloadAttributeError', 'AnnotationType', 'Annotation', 'TraceItem', ] class AnnotationType(Enum): """ The types of annotation, used by different loaders. FIELD is the name of a field INDEX is the numerical index of a value, in subscriptable objects- """ FIELD = 'field' INDEX = 'index' FORWARDREF = 'forwardref' KEY = 'key' VALUE = 'value' UNION = 'union' Annotation = NamedTuple('Annotation', [ ('annotation_type', AnnotationType), ('value', Union[str, int, Type]), ]) TraceItem = NamedTuple('TraceItem', [ ('value', Any), ('type_', Type), ('annotation', Optional[Annotation]), ]) class TypedloadException(Exception): """ Exception which exposes some extra fields. trace: It is a list of all the recursive invocations of load(), with the parameters used. Very useful to locate the issue. The annotation is used by complex loaders that call load() more than once, to indicate in which step the error occurred. For example a list loader will use it to indicate the index which had the exception, and a NamedTuple loader will use it to indicate the name of the field which generated the exception. value: contains the value that could not be loaded. type_: contains the type in which the value could not be loaded. exceptions: A list of exceptions that happened during the loading. This is for now only used by the Union loader, to list all the exceptions that occurred during the various attempts. """ def __init__( self, description: str, trace: Optional[List[TraceItem]] = None, value: Any=None, type_: Optional[Type] = None, exceptions: Optional[List['TypedloadException']] = None) -> None: super().__init__(description) self.trace = trace if trace else [] self.value = value self.type_ = type_ self.exceptions = exceptions if exceptions else [] @staticmethod def _path(trace: List[TraceItem]) -> str: ''' Compact representation of where in the data the exception happened ''' path = [] for i in trace: if i.annotation: path.append('[%d]' % i.annotation[1] if isinstance(i.annotation[1], int) else str(i.annotation[1])) else: path.append(str(None)) if len(path) == 1 and path[0] == str(None): return '.' elif len(path) > 1 and path[0] == str(None): path[0] = '' return '.'.join(path) def _subexceptions(self, indent: int, trace: List) -> str: ''' Recursive list of all exceptions that happened in the unions ''' spaces = ' ' * indent msg = spaces + 'Exceptions:\n' for i in self.exceptions: msg += i._firstline(indent + 1) + '\n' msg += spaces + ' ' 'Path: ' + self._path(self.trace + i.trace[1:]) + '\n' if i.exceptions: msg += i._subexceptions(indent + 1, self.trace + i.trace[1:]) return msg def _firstline(self, indent: int) -> str: ''' Returns error string and the path ''' spaces = ' ' * indent return '\n'.join(spaces + str(i) for i in self.args) def __str__(self) -> str: msg = self._firstline(0) msg += '\nPath: ' + self._path(self.trace) if self.exceptions: msg += '\n' + self._subexceptions(0, self.trace).rstrip() return msg class TypedloadValueError(TypedloadException, ValueError): """ Exception class, subclass of ValueError. See the documentation of TypedloadException for more details. """ def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) class TypedloadTypeError(TypedloadException, TypeError): """ Exception class, subclass of TypeError. See the documentation of TypedloadException for more details. """ def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) class TypedloadAttributeError(TypedloadException, AttributeError): """ Exception class, subclass of AttributeError. See the documentation of TypedloadException for more details. """ def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) typedload/typedload/datadumper.py0000664000175000017500000003020014721335070016561 0ustar salvosalvo""" typedload This module is the inverse of dataloader. It converts typed data structures to things that json can serialize. """ # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import datetime import ipaddress from inspect import signature from enum import Enum import pathlib import re from typing import * import uuid from .exceptions import TypedloadValueError from .typechecks import is_attrs, NONETYPE, is_literal __all__ = [ 'Dumper', ] class Dumper: """ This dumps data structures recursively using only basic types, lists and dictionaries. A value dumped in this way from a typed data structure can be loaded back using dataloader. hidedefault: Enabled by default. When enabled, does not include fields that have the same value as the default in the dump. isodates: Disabled by default. Will be enabled by default from version 3. When disabled, datetime.datetime, datetime.time, datetime.date are dumped as lists of ints. When enabled they are dumped as strings in ISO 8601 format. When enabled, timezone information will work. raiseconditionerrors: Enabled by default. Raises exceptions when evaluating a condition from an handler. When disabled, the exceptions are not raised and the condition is considered False. mangle_key: Defaults to 'name' Specifies which key is used into the metadata dictionaries to perform name-mangling. handlers: This is the list that the dumper uses to perform its task. The type is: List[ Tuple[ Callable[[Any], bool], Callable[['Dumper', Any, Any], Any] ] ] The elements are: Tuple[Condition, Dumper] Condition(value) -> Bool Dumper(dumper, value, value_type) -> simpler_value In most cases, it is sufficient to append new elements at the end, to handle more types. strconstructed: Set of types to dump to a string. These parameters can be set as named arguments in the constructor or they can be set later on. The constructor will accept any named argument, but only the documented ones have any effect. This is to allow custom handlers to have their own parameters as well. Because internal caches are used, after the first call to dump() these properties should no longer be modified. There is support for: * Basic python types (int, str, bool, float, NoneType) * NamedTuple, dataclasses, attrs, TypedDict * Dict[TypeA, TypeB] * Enum * List * Tuple * Set * FrozenSet * Path * IPv4Address, IPv6Address, IPv4Network, IPv6Network, IPv4Interface, IPv6Interface * datetime """ def __init__(self, **kwargs) -> None: self.basictypes = {int, bool, float, str, NONETYPE} self.hidedefault = True self.isodates = False # Which key is used in metadata to perform name mangling self.mangle_key = 'name' # Raise errors if the condition fails self.raiseconditionerrors = True # Things that become str. Needs to be done before handlers are created if 'strconstructed' in kwargs: self.strconstructed = kwargs.pop('strconstructed') else: self.strconstructed = { pathlib.Path, pathlib.PosixPath, pathlib.WindowsPath, ipaddress.IPv4Address, ipaddress.IPv6Address, ipaddress.IPv4Network, ipaddress.IPv6Network, ipaddress.IPv4Interface, ipaddress.IPv6Interface, uuid.UUID, } self.handlers = [ (lambda value: type(value) in self.basictypes, _identitydump), (lambda value: isinstance(value, tuple) and hasattr(value, '_fields') and hasattr(value, '_asdict'), _namedtupledump), (lambda value: '__dataclass_fields__' in dir(value), _dataclassdump), (lambda value: isinstance(value, (list, tuple, set, frozenset)), _iteratordump), (lambda value: isinstance(value, Enum), lambda l, value, t: l.dump(value.value)), (lambda value: isinstance(value, Dict), lambda l, value, t: {l.dump(k): l.dump(v) for k, v in value.items()}), (is_attrs, _attrdump), (lambda value: isinstance(value, (datetime.date, datetime.time)), _datetimedump), (lambda value: isinstance(value, datetime.timedelta), _timedeltadump), (lambda value: isinstance(value, re.Pattern), _patterndump), (lambda value: type(value) in self.strconstructed, lambda l, value, t: str(value)), ] # type: List[Tuple[Callable[[Any], bool], Callable[['Dumper', Any, Any], Any]|Callable[['Dumper', Any], Any]]] self._handlerscache = {} # type: Dict[Type[Any], Callable[['Dumper', Any, Any], Any]] self._dataclasscache = {} # type: Dict[Type[Any], Tuple[Set[str], Dict[str, Any], Dict[str, Any], Dict[str, str], Set[str], bool]] for k, v in kwargs.items(): setattr(self, k, v) def index(self, value: Any) -> int: """ Returns the index in the handlers list that matches the given value. If no condition matches, ValueError is raised. """ for i, cond in ((j[0], j[1][0]) for j in enumerate(self.handlers)): try: match = cond(value) except Exception: if self.raiseconditionerrors: raise match = False if match: return i raise TypedloadValueError('Unable to dump %s' % value, value=value, type_=type(value)) def dump(self, value: Any, annotated_type=Any) -> Any: """ Dump the typed data structure into its untyped equivalent. annotated_type contains the annotation for the value. It is not needed to provide it, but it can enable some faster code paths. """ t = type(value) try: func = self._handlerscache[t] except KeyError: index = self.index(value) f = self.handlers[index][1] # It has no type parameter, make a lambda if len(signature(f).parameters) == 2: import warnings warnings.warn( 'The type signature for the dump handlers has changed to include type hints\n' 'new handlers are: f(dumper, value, annotated_type)', DeprecationWarning ) func = lambda d, v, _: f(d, v) # type: ignore else: func = f # type: ignore self._handlerscache[t] = func # type: ignore return func(self, value, annotated_type) # type: ignore def _attrdump(d, value, t) -> Dict[str, Any]: r = {} for attr in value.__attrs_attrs__: attrval = getattr(value, attr.name) if not attr.repr: continue if d.hidedefault: if attrval == attr.default: continue elif hasattr(attr.default, 'factory') and attrval == attr.default.factory(): continue name = attr.metadata.get(d.mangle_key, attr.name) r[name] = d.dump(attrval) return r def _datetimedump(d: Dumper, value: Union[datetime.time, datetime.date, datetime.datetime], t): if d.isodates: return value.isoformat() import warnings warnings.warn( 'Dumping datetime classes as list of values is deprecated.\n' 'You are encouraged to dump with isodates=True\n' 'This will become the default in the next major version.', DeprecationWarning ) # datetime is subclass of date if isinstance(value, datetime.date) and not isinstance(value, datetime.datetime): return [value.year, value.month, value.day] if value.tzinfo is not None: raise NotImplementedError('Dumping of tzdata object is not supported') if isinstance(value, datetime.time): return [value.hour, value.minute, value.second, value.microsecond] # datetime.datetime return [value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond] def _timedeltadump(d: Dumper, value: datetime.timedelta, t) -> float: return value.total_seconds() def _patterndump(d: Dumper, value: re.Pattern, t): return value.pattern def _namedtupledump(d: Dumper, value, t) -> Dict[str, Any]: field_defaults = getattr(value, '_field_defaults', {}) # Named tuple, skip default values return { k: d.dump(v) for k, v in value._asdict().items() if not d.hidedefault or k not in field_defaults or field_defaults[k] != v } def _dataclassdump(d: Dumper, value, t) -> Dict[str, Any]: t = type(value) try: fields, defaults, type_hints, renames, needs_dump, hasdict = d._dataclasscache[t] except KeyError: from dataclasses import _MISSING_TYPE as DT_MISSING_TYPE fields = set(value.__dataclass_fields__.keys()) field_defaults = {k: v.default for k,v in value.__dataclass_fields__.items() if not isinstance (v.default, DT_MISSING_TYPE)} field_factories = {k: v.default_factory() for k,v in value.__dataclass_fields__.items() if not isinstance (v.default_factory, DT_MISSING_TYPE)} defaults = {**field_defaults, **field_factories} # Merge the two dictionaries type_hints = get_type_hints(t) renames = {k: v.metadata[d.mangle_key] for k,v in value.__dataclass_fields__.items() if d.mangle_key in v.metadata} # Fields to dump directly needs_dump = fields.difference({ k for k,v in value.__dataclass_fields__.items() if (v.type in d.basictypes and d.handlers[0][1] == _identitydump) or is_literal(v.type) }) hasdict = hasattr(value, '__dict__') d._dataclasscache[t] = (fields, defaults, type_hints, renames, needs_dump, hasdict) if hasdict: r = value.__dict__.copy() else: # Slow method if the __dict__ member is not present r = {f: getattr(value, f) for f in fields} for k in fields: if not d.hidedefault or k not in defaults or defaults[k] != r[k]: if k in needs_dump: r[k] = d.dump(r[k], type_hints[k]) else: del r[k] if renames: renamesqueue = [] for f in renames: if f in r: renamesqueue.append((renames[f], r.pop(f))) for k,v in renamesqueue: r[k] = v return r def _iteratordump(d: Dumper, value: Any, t: Any) -> List[Any]: if t != Any: try: itertypes = t.__args__ except AttributeError: itertypes = (Any,) else: itertypes = (Any,) # list[T] or tuple[T, ...] if (len(itertypes) == 1) or (len(itertypes) == 2 and itertypes[1] == ...): # type: ignore # This is true for lists/sets but not tuples itertype = itertypes[0] else: itertype = Any if itertype in d.basictypes and d.handlers[0][1] == _identitydump: # Iterable of basic types, unchanged default handler for basic types if isinstance(value, list): # Just copy the list if it's a list return value.copy() else: # Create a list and return it otherwise return list(value) return [d.dump(i) for i in value] def _identitydump(d: Dumper, value: Any, t: Any) -> Any: return value typedload/typedload/alias.py0000664000175000017500000000474414721335070015542 0ustar salvosalvo""" typedload You should not import this module before python3.12 It is meant to deal with TypeAliasType defined in PEP 695. """ # Copyright (C) 2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from functools import lru_cache, reduce from typing import List, Set, Tuple, FrozenSet from .typechecks import * # From 3.12 onwards try: from typing import TypeAliasType # type: ignore except ImportError: TypeAliasType = None __all__ = [ 'unalias' ] if TypeAliasType: def is_alias(t) -> bool: ''' It returns true if the type is an alias ''' return isinstance(t, TypeAliasType) else: def is_alias(t) -> bool: ''' Not supported on this version of python ''' return False _TUPLETYPE = Tuple[int] @lru_cache def unalias(t): ''' It tries to resolve the alias. For example type i = tuple[list[int | float], ...] will be converted into the actual Tuple[List[Union[int, float]], ...] that is possible to match with type handlers. ''' # Resolve all nested stuff (hopefully) if is_union(t): # This creates a real union at runtime t = reduce((lambda a, b: a | b), (unalias(i) for i in t.__args__)) elif is_list(t): t = List[unalias(t.__args__[0])] # type: ignore elif is_set(t): t = Set[unalias(t.__args__[0])] # type: ignore elif is_tuple(t): # This is an horrible hack to create a Tuple type # with the parameters I want. # # TODO # From 3.11 this can be replaced with Tuple[*args] args = tuple((unalias(i) for i in t.__args__)) t = _TUPLETYPE.copy_with(args) # type: ignore elif is_frozenset(t): t = FrozenSet[unalias(t.__args__[0])] # type: ignore elif is_alias(t): t = unalias(t.__value__) return t typedload/typedload/dataloader.py0000664000175000017500000010702614721335070016546 0ustar salvosalvo""" typedload Module to load data into typed data structures """ # Copyright (C) 2018-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import datetime from enum import Enum import ipaddress from itertools import compress, count, repeat from pathlib import Path import re from typing import * import uuid from .exceptions import * from .typechecks import * from .typechecks import discriminatorliterals from .helpers import tname try: # A dirty trick # # The alias module has a syntax that won't work on # older python versions, so we only import it # from 3.12 onwards (which is also where it can be used) from typing import TypeAliasType # type: ignore from .alias import unalias # type: ignore except ImportError: unalias = None # type: ignore __all__ = [ 'Loader', ] T = TypeVar('T') class Loader: """ A loader object that recursively loads data into the desired type. basictypes: a set of types that are considered as building blocks for everything else and do not need to be converted further. If you are not loading from json, you probably want to add bytes to the set. failonextra: Disabled by default. When enabled, the loader will raise exceptions if there are fields in the data that are not being used by the type. basiccast: Enabled by default. When disabled, instead of trying to perform casts, exceptions will be raised. Since many json seem to encode numbers as strings, to avoid extra complications this functionality is provided. If you know that your original data is encoded properly, it is better to disable this. dictequivalence: Enabled by default. Automatically convert dict-like classes to dictionary when loading. This enables them to be loaded into other classes. At the moment it supports: argparse.Namespace raiseconditionerrors: Enabled by default. Raises exceptions when evaluating a condition from an handler. When disabled, the exceptions are not raised and the condition is considered False. uniondebugconflict: Disabled by default When enabled, all the possible types for the unions are evaluated instead of stopping at the first that works. If more than one type in the union works, an error is raised because the types are conflicting and the union might return different types with the same input value. This option makes the loading slower and is only to be used when debugging issues. mangle_key: Defaults to 'name' Specifies which key is used into the metadata dictionaries to perform name-mangling. handlers: This is the list that the loader uses to perform its task. The type is: List[ Tuple[ Callable[[Type[T]], bool], Callable[['Loader', Any, Type[T]], T] ] ] The elements are: Tuple[Condition,Loader] Condition(type) -> Bool Loader(loader, value, type) -> type In most cases, it is sufficient to append new elements at the end, to handle more types. There is an internal cache to speed up lookup, so after the first call to load, this should no longer be modified. strconstructed: Set of types to construct from a string. frefs: Dictionary to resolve ForwardRef. Something like class Node(NamedTuple): next: Optional['Node'] requires a ForwardRef (also in python3.7), which means that the type is stored as string and must be resolved at runtime. This dictionary contains the names of the types as keys, and the actual types as values. A loader object by default starts with an empty dictionary and fills it with the types it encounters, but it is possible to manually add more types to the dictionary. Setting this to None disables any support for ForwardRef. Reusing the same loader object on unrelated types might cause failures, if the types are different but use the same names. pep563: Set to true to use __future__.annotations WARNING: DEPRECATED Support for this might be removed in any future release without notice. Check deferred evaluation in the documentation for more details. This will make typedload much slower. This PEP is broken and superseeded by PEP649. Do not report bugs about this "feature". It's not here to stay. These parameters can be set as named arguments in the constructor or they can be set later on. The constructor will accept any named argument, but only the documented ones have any effect. This is to allow custom handlers to have their own parameters as well. Because internal caches are used, after the first call to load() these properties should no longer be modified. Using unions is complicated. The best is to use tagged unions using a Literal field. If the types in the union are too similar to each other, it is easy to obtain an unexpected type. """ def __init__(self, **kwargs) -> None: # Types that do not need conversion self.basictypes = {int, bool, float, str, NONETYPE} # If true, it attempts to do casting of basic types # otherwise an exception is raised self.basiccast = True # Raise errors if the value has more data than the # type expects. # By default the extra data is ignored. self.failonextra = False # Raise errors if the condition fails self.raiseconditionerrors = True # Forward refs dictionary self.frefs = {} # type: Optional[Dict[str, Type]] # Enable conversion of dict-like things to dicts, before loading self.dictequivalence = True # Which key is used in metadata to perform name mangling self.mangle_key = 'name' # Fail if multiple types work within the union self.uniondebugconflict = False # Objects loaded from a string self.strconstructed = { Path, ipaddress.IPv4Address, ipaddress.IPv6Address, ipaddress.IPv4Network, ipaddress.IPv6Network, ipaddress.IPv4Interface, ipaddress.IPv6Interface, uuid.UUID, } # Bah self.pep563 = False # The list of handlers to use to load the data. # It gets iterated in order, and the first condition # that matches is used to load the value. self.handlers = [ (is_nonetype, _noneload), (is_union, _unionload), (lambda type_: type_ in self.basictypes, _basicload), (is_enum, _enumload), (is_tuple, _tupleload), (is_list, lambda l, value, type_: _iterload(l, value, type_, list)), (is_dict, _dictload), (is_set, lambda l, value, type_: _iterload(l, value, type_, set)), (is_frozenset, lambda l, value, type_: _iterload(l, value, type_, frozenset)), (is_namedtuple, _namedtupleload), (is_dataclass, _dataclassload), (is_forwardref, _forwardrefload), (is_literal, _literalload), (is_typeddict, _typeddictload), (lambda type_: type_ in {datetime.date, datetime.time, datetime.datetime}, _datetimeload), (is_pattern, _patternload), (lambda type_: type_ == datetime.timedelta, _timedeltaload), (lambda type_: type_ in self.strconstructed, _strconstructload), (is_attrs, _attrload), (is_any, _anyload), (is_newtype, _newtypeload), ] # type: List[Tuple[Callable[[Any], bool], Callable[[Loader, Any, Any], Any]]] for k, v in kwargs.items(): setattr(self, k, v) self._indexcache = {} # type: Dict[Any, Callable[[Loader, Any, Any], Any]] self._objfieldscache = {} # type: Dict[Type, Any] self._unionload_discriminatorcache = {} # type: Dict[int, Tuple[Optional[str], Optional[Dict[Any, Type]]]] self._union_sorted_args_cache = {} # type: Dict[int, List[Type]] def index(self, type_: Type[T]) -> int: """ Returns the index in the handlers list that matches the given type. If no condition matches, ValueError is raised. """ for i, cond in ((q[0], q[1][0]) for q in enumerate(self.handlers)): try: match = cond(type_) except Exception: if self.raiseconditionerrors: raise match = False if match: return i raise ValueError('No matching condition found') def _index_and_cache(self, type_: Type[T]) -> int: """ Same as index() but the result is added to the cache """ r = self.index(type_) self._indexcache[type_] = self.handlers[r][1] return r def load(self, value: Any, type_: Type[T], *, annotation: Optional[Annotation] = None) -> T: """ Loads value into the typed data structure. TypeError is raised if there is no known way to treat type_, otherwise all errors raise a ValueError. annotation is used by recursive calls to track which path was being executed in case of exceptions. It is only needed when calling load recursively from a custom handler. """ if unalias: type_ = unalias(type_) # type: ignore cached_f = self._indexcache.get(type_) if cached_f is not None: func = cached_f else: try: index = self.index(type_) except ValueError: raise TypedloadTypeError( 'Cannot deal with value of type %s' % tname(type_), value=value, type_=type_ ) func = self._indexcache[type_] = self.handlers[index][1] # Add type to known types, to resolve ForwardRef later on if self.frefs is not None and hasattr(type_, '__name__'): typename = type_.__name__ if typename not in self.frefs: self.frefs[typename] = type_ try: return func(self, value, type_) except Exception as e: assert isinstance(e, TypedloadException) e.trace.insert(0, TraceItem(value, type_, annotation)) raise e def _forwardrefload(l: Loader, value: Any, type_) -> Any: """ This resolves a ForwardRef. It just looks up the type in the dictionary of known types and loads the value using that. """ if l.frefs is None: raise TypedloadException('ForwardRef resolving is disabled for the loader', value=value, type_=type_) tname = type_.__forward_arg__ # type: ignore t = l.frefs.get(tname) if t is None: raise TypedloadValueError( "ForwardRef '%s' unknown" % tname, value=value, type_=type_ ) return l.load(value, t, annotation=Annotation(AnnotationType.FORWARDREF, tname)) def _anyload(l: Loader, value: Any, type_) -> Any: return value def _literalload(l: Loader, value: Any, type_) -> Any: """ Checks if the value is within the allowed literals and returns it. """ if value in type_.__args__: return value raise TypedloadValueError('Not one of the allowed values in %s' % tname(type_), value=value, type_=type_) def _basicload(l: Loader, value: Any, type_) -> Any: """ This converts a value into a basic type. In theory it does nothing, but it performs type checking and raises if conditions fail. It also attempts casting, if enabled. """ if type(value) != type_: if l.basiccast: try: return type_(value) except ValueError as e: raise TypedloadValueError(str(e), value=value, type_=type_) except TypeError as e: raise TypedloadTypeError(str(e), value=value, type_=type_) except Exception as e: raise TypedloadException(str(e), value=value, type_=type_) else: raise TypedloadValueError('Got %s of type %s, expected %s' % (repr(value), tname(type(value)), tname(type_)), value=value, type_=type_) return value def _dictload(l: Loader, value: Any, type_) -> Dict: """ This loads into something like Dict[str,str] Recursively loads both keys and values. """ key_type, value_type = type_.__args__ key_type_basic = key_type in l.basictypes value_type_basic = value_type in l.basictypes try: key_f = l._indexcache[key_type] except KeyError: try: key_f = l._indexcache[key_type] = l.handlers[l.index(key_type)][1] except ValueError: raise TypedloadValueError( 'Cannot deal with value of type %s (key of %s)' % (tname(key_type), tname(type_)), value=value, type_=key_type ) # Same thing for the value try: value_f = l._indexcache[value_type] except KeyError: try: value_f = l._indexcache[value_type] = l.handlers[l.index(value_type)][1] except ValueError: raise TypedloadValueError( 'Cannot deal with value of type %s (value of %s)' % (tname(value_type), tname(type_)), value=value, type_=value_type ) value = _dictequivalence(l, value) # Try fast load try: return { k if key_type_basic and isinstance(k, key_type) else key_f(l, k, key_type): \ v if value_type_basic and isinstance(v, value_type) else value_f(l, v, value_type) \ for k, v in value.items() } except Exception: # Failed, do the slow method with exception tracking pass try: return { l.load(k, key_type, annotation=Annotation(AnnotationType.KEY, k)): l.load(v, value_type, annotation=Annotation(AnnotationType.VALUE, v)) for k, v in value.items()} except AttributeError as e: raise TypedloadAttributeError(str(e), type_=type_, value=value) def _tupleload(l: Loader, value: Any, type_) -> Tuple: """ This loads into something like Tuple[int,str] """ args = type_.__args__ len_args = len(args) if len_args == 2 and args[1] == ...: # Tuple[something, ...] return _iterload(l, value, type_, tuple) # Tuple[something, something, somethingelse] if isinstance(value, dict): raise TypedloadTypeError('Unable to load dictionary as a tuple', value=value, type_=type_) len_value = len(value) if l.failonextra and len_value > len_args: raise TypedloadValueError('Value is too long for type %s' % tname(type_), value=value, type_=type_) elif len_value < len_args: raise TypedloadValueError('Value is too short for type %s' % tname(type_), value=value, type_=type_) ctr = count(1) # Keep track of the position in the tuple try: return tuple(v if t in l.basictypes and type(v) == t else (l._indexcache.get(t) or l.handlers[l._index_and_cache(t)][1])(l, v, t) for v, t in zip( compress(value, ctr), args ) ) except TypedloadException as e: index = next(ctr) - 2 annotation = Annotation(AnnotationType.INDEX, index) e.trace.insert(0, TraceItem(value, type_, annotation)) raise e except TypeError as e: raise TypedloadTypeError(str(e), value=value, type_=type_) except Exception as e: raise TypedloadTypeError('Exception is not a subclass of TypedloadException. Make sure all handlers only raise TypedloadException') def _mangle_names(namesmap: Dict[str, str], value: Dict[str, Any], failonextra: bool) -> Dict[str, Any]: """ Mangling names of a dictionary. The dictionary is copied internally. Namesmap is the mapping to be applied, in the format [dataname] = pyname """ if not namesmap: return value r = {} # Disallow the python names if they are in the map skip = set(namesmap.values()) for k, v in value.items(): if k in skip and k not in namesmap: if failonextra: raise ValueError('Extra field: %s' % k) else: continue if k in namesmap: k = namesmap[k] r[k] = v return r def _dataclassload(l: Loader, value: Dict[str, Any], type_) -> Any: """ This loads a Dict[str, Any] into a NamedTuple. """ try: fields, necessary_fields, type_hints, transforms = l._objfieldscache[type_] except KeyError: fields = set(type_.__dataclass_fields__.keys()) necessary_fields = {k for k,v in type_.__dataclass_fields__.items() if v.init == True and # Is a field for the constructor v.default == v.default_factory # Has no default or factory } if l.pep563: type_hints = get_type_hints(type_) else: if unalias: type_hints = {k: unalias(v.type) for k,v in type_.__dataclass_fields__.items()} else: type_hints = {k: v.type for k,v in type_.__dataclass_fields__.items()} #Name mangling # Prepare the list of the needed name changes transforms = {} for pyname in fields: if type_.__dataclass_fields__[pyname].metadata: name = type_.__dataclass_fields__[pyname].metadata.get(l.mangle_key) if name: transforms[name] = pyname l._objfieldscache[type_] = (fields, necessary_fields, type_hints, transforms) if transforms: try: value = _mangle_names(transforms, value, l.failonextra) except ValueError as e: raise TypedloadValueError(str(e), value=value, type_=type_) except AttributeError as e: raise TypedloadAttributeError(str(e), value=value, type_=type_) return _objloader(l, fields, necessary_fields, type_hints, value, type_, False) def _dictequivalence(l: Loader, value: Any) -> Any: ''' Helper function to convert classes that are functionally the same as a dict into a dict. At the moment the only class that can be converted is argparse.Namespace. in all other cases this simply returns value. ''' # Convert argparse.Namespace to dictionary if l.dictequivalence and hasattr(value, '_get_kwargs'): return {k: v for k,v in value._get_kwargs()} return value def _objloader(l: Loader, fields: Set[str], necessary_fields: Set[str], type_hints, value: Any, type_, early_needed_fields_check: bool) -> Any: ''' Helper function to load dict-like data into an object. ''' if l.dictequivalence and not isinstance(value, dict): newvalue = _dictequivalence(l, value) if newvalue is value: raise TypedloadAttributeError('Not a dictionary: %s' % value, value=value, type_=type_) else: value = newvalue if early_needed_fields_check or l.failonextra: vfields = set(value.keys()) if early_needed_fields_check and len(necessary_fields.intersection(vfields)) != len(necessary_fields): raise TypedloadTypeError( 'Value does not contain fields: %s which are necessary for type %s' % ( necessary_fields.difference(vfields), tname(type_) ), value=value, type_=type_, ) if l.failonextra and len(extra_fields := vfields.difference(fields)): extra = ', '.join(extra_fields) raise TypedloadTypeError( 'Dictionary has unrecognized fields: %s and cannot be loaded into %s' % (extra, tname(type_)), value=value, type_=type_, ) params = {} for k, v in value.items(): if k not in fields: # Field in value is not in the type continue # loading field directly, skipping load() field_type = type_hints[k] try: loader_f = l._indexcache[field_type] except KeyError: try: loader_f = l._indexcache[field_type] = l.handlers[l.index(field_type)][1] except ValueError: raise TypedloadTypeError( 'Cannot deal with value of type %s' % tname(field_type), value=value, type_=field_type ) try: params[k] = loader_f(l, v, field_type) except TypedloadException as e: annotation=Annotation(AnnotationType.FIELD, k) e.trace.insert(0, TraceItem(value, type_, annotation)) raise e try: return type_(**params) except TypeError as e: vfields = set(value.keys()) # Check the necessary fields only if there was an error loading if len(necessary_fields.intersection(vfields)) != len(necessary_fields): raise TypedloadTypeError( 'Value does not contain fields: %s which are necessary for type %s' % ( necessary_fields.difference(vfields), tname(type_) ), value=value, type_=type_, ) raise TypedloadTypeError(e) except ValueError as e: raise TypedloadValueError(e) def _namedtupleload(l: Loader, value: Any, type_) -> Any: """ This loads a Dict[str, Any] into a NamedTuple. """ try: fields, necessary_fields, type_hints = l._objfieldscache[type_] except KeyError: if l.pep563: type_hints = get_type_hints(type_) else: if unalias: type_hints = {k: unalias(v) for k,v in type_.__annotations__.items()} else: type_hints = type_.__annotations__ fields = set(type_hints.keys()) optional_fields = set(getattr(type_, '_field_defaults', {}).keys()) necessary_fields = fields.difference(optional_fields) l._objfieldscache[type_] = fields, necessary_fields, type_hints return _objloader(l, fields, necessary_fields, type_hints, value, type_, False) def _typeddictload(l: Loader, value: Any, type_) -> Any: """ This loads a Dict[str, Any] into a NamedTuple. """ try: fields, necessary_fields, type_hints = l._objfieldscache[type_] except KeyError: if l.pep563: type_hints = get_type_hints(type_) else: type_hints = type_.__annotations__ fields = set(type_hints.keys()) if hasattr(type_, '__required_keys__') and hasattr(type_, '__optional_keys__'): # TypedDict, since 3.9 necessary_fields = set(type_.__required_keys__) elif not type_.__total__: necessary_fields = set() else: necessary_fields = fields # Resolve the NotRequired/Required stuff for k, v in type_hints.items(): while True: if is_notrequired(v): v = type_hints[k] = notrequiredtype(v) necessary_fields.discard(k) elif is_required(v): v = type_hints[k] = requiredtype(v) necessary_fields.add(k) elif is_readonly(v): v = type_hints[k] = readonlytype(v) else: break if unalias: type_hints = {k: unalias(v) for k, v in type_hints.items()} l._objfieldscache[type_] = fields, necessary_fields, type_hints return _objloader(l, fields, necessary_fields, type_hints, value, type_, True) def _unionload(l: Loader, value: Any, type_) -> Any: """ Loads a value into a union. Basically this iterates all the types inside the union, until one that doesn't raise an exception is found. If no suitable type is found, an exception is raised. """ args = uniontypes(type_) value_type = type(value) type_id = id(type_) # Do not convert basic types, if possible if value_type in l.basictypes and value_type in args: return value exceptions = [] # Give a score to the types try: sorted_args = l._union_sorted_args_cache[type_id] # type: List[Type] except KeyError: sorted_args = list(args) sorted_args.sort(key=lambda i: i in l.basictypes) l._union_sorted_args_cache[type_id] = sorted_args # For object types, bump up the type whose literal is matching if hasattr(value, 'get'): # Seems we have an object # Bump up if the Literal field matches try: discriminatorscache = l._unionload_discriminatorcache[type_id] # type: Tuple[Optional[str], Optional[Dict[Any, Type]]] # First time generate the deep inspection for literal except KeyError: # type → {key: valueset} data = {t: discriminatorliterals(t) for t in args} # shared keys that have literals in every object of the union keys = set.intersection(*(set(v.keys()) for v in data.values())) cachedict = {} if keys: key = keys.pop() for t, d in data.items(): for literal in d[key]: cachedict[literal] = t discriminatorscache = key, cachedict else: discriminatorscache = None, None l._unionload_discriminatorcache[type_id] = discriminatorscache # Cache is created, use it # It's a tuple key, {value: type} if discriminatorscache[1]: preferredtype = discriminatorscache[1].get(value.get(discriminatorscache[0])) if preferredtype: # Place best value on top sorted_args.remove(preferredtype) sorted_args.insert(0, preferredtype) # Try all types loaded_count = 0 r = None for t in sorted_args: try: # Skip calling load() try: f = l._indexcache[t] except KeyError: try: f = l._indexcache[t] = l.handlers[l.index(t)][1] except ValueError: raise TypedloadValueError( 'Cannot deal with value of type %s (key of %s)' % (tname(t), tname(type_)), value=value, type_=t ) r = f(l, value, t) loaded_count += 1 if not l.uniondebugconflict: # Do not try more if we are not debugging break except TypedloadException as e: annotation = Annotation(AnnotationType.UNION, t) e.trace.insert(0, TraceItem(value, type_, annotation)) exceptions.append(e) if loaded_count == 1: # Loaded only once, all good return r elif loaded_count == 0: # Could not be loaded raise TypedloadValueError( 'Value of %s could not be loaded into %s' % (tname(value_type), tname(type_)), value=value, type_=type_, exceptions=exceptions ) else: # Loaded more than once, conflict raise TypedloadTypeError( 'Value of %s could be loaded into %s %d times' % (tname(value_type), tname(type_), loaded_count), value=value, type_=type_, exceptions=exceptions ) def _enumload(l: Loader, value: Any, type_) -> Enum: """ This loads something into an Enum. It tries with basic types first. If that fails, it tries to look for type annotations inside the Enum, and tries to use those to load the value into something that is compatible with the Enum. Of course if that fails too, a ValueError is raised. """ try: # Try naïve conversion return type_(value) except Exception: pass # Try with the typing hints exceptions = [] for _, t in get_type_hints(type_).items(): try: return type_(l.load(value, t, annotation=Annotation(AnnotationType.UNION, t))) except Exception as e: exceptions.append(e) if len(type_.__members__) <= 10 and all(type(i.value) in l.basictypes for i in type_.__members__.values()): lst = '\nValue %s not between: ' % repr(value) + \ ', '.join(repr(i.value) for i in type_.__members__.values()) else: lst = '' raise TypedloadValueError( 'Value of %s could not be loaded into %s%s' % (tname(type(value)), tname(type_), lst), value=value, type_=type_, exceptions=exceptions ) def _noneload(l: Loader, value: Any, type_) -> None: """ Loads a value that can only be None, so it fails if it isn't """ if value is None: return None raise TypedloadValueError('Not None', value=value, type_=type_) def _datetimeload(l: Loader, value: Any, type_) -> Union[datetime.date, datetime.time, datetime.datetime]: try: if isinstance(value, str): return type_.fromisoformat(value) else: # This might be removed at some point in the future, but it will break data compatibility return type_(*value) except TypeError as e: raise TypedloadTypeError(str(e), type_=type_, value=value) except ValueError as e: raise TypedloadValueError(str(e), type_=type_, value=value) def _patternload(l: Loader, value: Any, type_) -> re.Pattern: if hasattr(type, "__args__"): (input_type,) = type_.__args__ if input_type in {bytes, str} and type(value) != input_type: raise TypedloadValueError('Got %s of type %s, expected %s' % (repr(value), tname(type(value)), tname(type_)), value=value, type_=type_) try: return re.compile(value) except re.error as e: raise TypedloadException(str(e), value=value, type_=type_) except TypeError as e: raise TypedloadTypeError(str(e), value=value, type_=type_) def _timedeltaload(l: Loader, value, type_) -> datetime.timedelta: try: return type_(0, value) except TypeError as e: raise TypedloadTypeError(str(e), type_=type_, value=value) def _get_attr_converter_type(c: "Callable"): """ c is a converter function passed to an attr field it is supposed to have 1 parameter only If it's typed, return the type of the parameter. Otherwise return Any """ hints = get_type_hints(c) if len(hints) > 0 and len(hints) <= 2: if 'return' in hints: del hints['return'] return next(iter(hints.values())) return Any def _attrload(l: Loader, value: Any, type_) -> Any: try: fields, necessary_fields, type_hints, namesmap = l._objfieldscache[type_] except KeyError: from attr._make import _Nothing as NOTHING fields = {i.name for i in type_.__attrs_attrs__} necessary_fields = set() if unalias: type_hints = {i.name: (_get_attr_converter_type(i.converter) if i.converter else unalias(i.type)) for i in type_.__attrs_attrs__} else: type_hints = {i.name: (_get_attr_converter_type(i.converter) if i.converter else i.type) for i in type_.__attrs_attrs__} namesmap = {} for attribute in type_.__attrs_attrs__: if type(attribute.default) is NOTHING and attribute.init: necessary_fields.add(attribute.name) # Manage name mangling if l.mangle_key in attribute.metadata: namesmap[attribute.metadata[l.mangle_key]] = attribute.name l._objfieldscache[type_] = fields, necessary_fields, type_hints, namesmap if namesmap: try: value = _mangle_names(namesmap, value, l.failonextra) except ValueError as e: raise TypedloadValueError(str(e), value=value, type_=type_) except AttributeError as e: raise TypedloadAttributeError(str(e), value=value, type_=type_) return _objloader(l, fields, necessary_fields, type_hints, value, type_, False) def _strconstructload(l: Loader, value, type_): """ Loader for all the types taking a string as single constructor parameter """ try: return type_(value) except ValueError as e: raise TypedloadValueError(str(e), type_=type_, value=value) except TypeError as e: raise TypedloadTypeError(str(e), type_=type_, value=value) except Exception as e: raise TypedloadException(str(e), type_=type_, value=value) def _newtypeload(l: Loader, value: Any, type_) -> Any: return l.load(value, type_.__supertype__) def _iterload(l: Loader, value: Any, type_, function) -> Any: """ Generic code to load iterables. function is for example list, tuple, set. The call to generate the destination type from an iterable. """ if isinstance(value, dict): raise TypedloadTypeError('Unable to load dictionary as an iterable', value=value, type_=type_) t = type_.__args__[0] # Get function pointer for the handler try: f = l._indexcache[t] except KeyError: try: f = l._indexcache[t] = l.handlers[l.index(t)][1] except ValueError: raise TypedloadTypeError( 'Cannot deal with value of type %s' % tname(t), value=value, type_=t, ) # load calling the handler directly, skipping load() try: ctr = count(1) if t in l.basictypes: if function is list: # Copy paste but a list comprehension directly instead of a generic one return [i if isinstance(i, t) else f(l, i, t) for i in compress(value, ctr)] elif function is set: return {i if isinstance(i, t) else f(l, i, t) for i in compress(value, ctr)} return function((i if isinstance(i, t) else f(l, i, t) for i in compress(value, ctr))) elif is_union(t) and (types := set(uniontypes(t))).issubset(l.basictypes): if function is list: return [i if type(i) in types else f(l, i, t) for i in compress(value, ctr)] elif function is set: return {i if type(i) in types else f(l, i, t) for i in compress(value, ctr)} return function((i if type(i) in types else f(l, i, t) for i in compress(value, ctr))) else: return function(map(f, repeat(l), compress(value, ctr), repeat(t))) except TypedloadException as e: index = next(ctr) - 2 annotation = Annotation(AnnotationType.INDEX, index) e.trace.insert(0, TraceItem(value, type_, annotation)) raise e except TypeError as e: raise TypedloadTypeError(str(e), value=value, type_=type_) except Exception as e: raise TypedloadTypeError('Exception is not a subclass of TypedloadException. Make sure all handlers only raise TypedloadException') typedload/typedload/py.typed0000664000175000017500000000000014721335070015553 0ustar salvosalvotypedload/typedload/typechecks.py0000664000175000017500000002034114721335070016602 0ustar salvosalvo""" typedload Module to check types, mostly from the typing module. For example is_list(List) and is_list(List[int]) return True. It is not the same as isinstance(), it wants types, not instances. It is expected that is_list(list) returns False, since it shouldn't be used for type hints. The module is useful because there is no public API to do those checks, and it protects the user from the ever changing internal representation used in different versions of Python. """ # Copyright (C) 2019-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli import sys from enum import Enum from re import Pattern from typing import Any, Tuple, Union, Set, List, Dict, Type, FrozenSet, NewType __all__ = [ 'is_any', 'is_pattern', 'is_attrs', 'is_dataclass', 'is_dict', 'is_enum', 'is_forwardref', 'is_frozenset', 'is_list', 'is_literal', 'is_namedtuple', 'is_nonetype', 'is_set', 'is_tuple', 'is_union', 'is_typeddict', 'is_newtype', 'is_optional', 'is_notrequired', 'is_required', 'is_readonly', 'notrequiredtype', 'requiredtype', 'readonlytype', 'uniontypes', 'literalvalues', 'NONETYPE', 'HAS_TUPLEARGS', 'HAS_UNIONSUBCLASS', ] from typing import ForwardRef, Literal from typing import _TypedDictMeta # type: ignore UnionType = None # type: Any try: # Since 3.10 from types import UnionType # type: ignore except ImportError: pass try: # Since 3.11 from typing import NotRequired, Required # type: ignore except ImportError: NotRequired = None Required = None try: # Since 3.13 from typing import ReadOnly # type: ignore except ImportError: ReadOnly = None HAS_TUPLEARGS = True # Legacy, used to be dependant on python version, but I exported the symbol NONETYPE = type(None) # type: Any HAS_UNIONSUBCLASS = False def is_tuple(type_: Any) -> bool: ''' Tuple[int, str] Tuple ''' return _generic_type_check(type_, tuple, Tuple) if UnionType: # Uniontype is 3.10 defined on 3.10 and None otherwise def is_union(type_: Any) -> bool: ''' Union[A, B] Union Optional[A] A | B ''' return getattr(type_, '__origin__', None) == Union or getattr(type_, '__class__', None) == UnionType else: def is_union(type_: Any) -> bool: ''' Union[A, B] Union Optional[A] ''' # Uniontype is 3.10 defined on 3.10 and None otherwise return getattr(type_, '__origin__', None) == Union def is_optional(type_: Any) -> bool: ''' Optional[int] int | None Note that Optional is just a Union, so if is_optional is True then also is_union will be True ''' return is_union(type_) and (len(type_.__args__) == 2) and NONETYPE in type_.__args__ def is_nonetype(type_: Any) -> bool: ''' type_ == type(None) ''' return type_ == NONETYPE def _generic_type_check(type_: Any, native, from_typing) -> bool: return getattr(type_, '__origin__', None) in {native, from_typing} or getattr(type_, '__extra__', None) == native def is_list(type_: Any) -> bool: ''' List[A] List ''' return _generic_type_check(type_, list, List) def is_dict(type_: Any) -> bool: ''' Dict[A, B] Dict ''' return _generic_type_check(type_, dict, Dict) def is_set(type_: Any) -> bool: ''' Set[A] Set ''' return _generic_type_check(type_, set, Set) def is_frozenset(type_: Any) -> bool: ''' FrozenSet[A] FrozenSet ''' return _generic_type_check(type_, frozenset, FrozenSet) def is_enum(type_: Any) -> bool: ''' Check if the class is a subclass of Enum ''' try: return issubclass(type_, Enum) except TypeError: return False def is_namedtuple(type_: Any) -> bool: ''' Generated with typing.NamedTuple ''' try: subclass = issubclass(type_, tuple) except TypeError: subclass = False return subclass and hasattr(type_, '__annotations__') and hasattr(type_, '_fields') def is_dataclass(type_: Any) -> bool: ''' check if it's generated with dataclass decorator ''' return hasattr(type_, '__dataclass_fields__') def is_forwardref(type_: Any) -> bool: ''' Check if it's a ForwardRef. They are unresolved types passed as strings, supposed to be resolved into types at a later moment ''' return type(type_) == ForwardRef def is_attrs(type_: Any) -> bool: ''' Check if the type is obtained with an @attr.s decorator ''' return hasattr(type_, '__attrs_attrs__') if sys.version_info > (3, 10, 0): def is_newtype(type_: Any) -> bool: return type(type_) == NewType else: def is_newtype(type_: Any) -> bool: return hasattr(type_, '__supertype__') def uniontypes(type_: Any) -> Tuple[Type[Any], ...]: ''' Returns the types of a Union. ''' return type_.__args__ def literalvalues(type_: Any) -> Set[Any]: ''' Returns the values of a Literal Raises ValueError if the argument is not a Literal ''' if not is_literal(type_): raise ValueError('Not a Literal: ' + str(type_)) return set(type_.__args__) def is_literal(type_: Any) -> bool: ''' Check if the type is a typing.Literal ''' return getattr(type_, '__origin__', None) == Literal def is_pattern(type_: Any) -> bool: ''' Check if the type is a re.Pattern ''' return type_ == Pattern or getattr(type_, "__origin__", None) == Pattern def is_typeddict(type_: Any) -> bool: ''' Check if it is a typing.TypedDict ''' return isinstance(type_, _TypedDictMeta) def is_any(type_: Any) -> bool: ''' Check if it is a typing.Any ''' return type_ == Any if ReadOnly: def is_readonly(type_: Any) -> bool: ''' Check if it's typing.ReadOnly or typing_extensions.ReadOnly ''' return getattr(type_, '__origin__', None) == ReadOnly else: def is_readonly(type_: Any) -> bool: ''' Returns False. ReadOnly is not defined on this platform. ''' return False if NotRequired: def is_notrequired(type_: Any) -> bool: ''' Check if it's typing.NotRequired or typing_extensions.NotRequired ''' return getattr(type_, '__origin__', None) == NotRequired def is_required(type_: Any) -> bool: ''' Check if it's typing.Required or typing_extensions.Required ''' return getattr(type_, '__origin__', None) == Required else: def is_notrequired(type_: Any) -> bool: ''' Returns False. NotRequired is not defined on this platform. ''' return False def is_required(type_: Any) -> bool: ''' Returns False Required is not defined on this platform. ''' return False def notrequiredtype(type_: Any) -> Type[Any]: ''' Return the type wrapped by Required/NotRequired/ReadOnly ''' return type_.__args__[0] readonlytype = requiredtype = notrequiredtype def discriminatorliterals(type_: Any) -> Dict[str, Set[Any]]: """ Takes an object type (NamedTuple, TypedDict, attrs, dataclass) and returns which fields take a literal and which values are allowed by the literal. For unknown types, an empty dictionary is returned. """ # Give up if the object is unknown try: d = type_.__annotations__.items() except AttributeError: return {} r = {} for k, v in d: if not is_literal(v): continue r[k] = literalvalues(v) return r typedload/typedload/__init__.py0000664000175000017500000001304714721335070016204 0ustar salvosalvo""" typedload ========= This library loads Python data structures into typed data structures, enforcing a schema. The main purpose is to load things that come from json, bson or similar into NamedTuple or Dataclass. For example this Json: { 'users': [ { 'username': 'salvo', 'shell': 'bash', 'sessions': ['pts/4', 'tty7', 'pts/6'] }, { 'username': 'lop' } ], } Can be treated more easily if loaded into this: class User(NamedTuple): username: str shell: str = 'bash' sessions: List[str] = [] class Logins(NamedTuple): users: List[User] And can then be loaded with typedload.load(data, Logins) Simple API ========== typedload.load() and typedload.dump() are functions to quickly load and dump data using the default objects. They create a new loader/dumper object with default parameters, and discard it after. Classes ======= The loader and dumper classes expose a number of attributes that can be customised to tweak their behaviour. Supported datatypes =================== There is support for: * Basic python types (int, str, bool, float, NoneType) * NamedTuple * Enum * Optional[SomeType] * List[SomeType] * Dict[TypeA, TypeB] * Tuple[TypeA, TypeB, TypeC] * Tuple[SomeType, ...] * Set[SomeType] * Union[TypeA, TypeB] * ForwardRef * Literal * Dataclass * attrs * TypedDict * datetime * re.Pattern * Path * IPv4Address, IPv6Address Handlers ======== To work with other datatypes, handlers can be used. The handlers' list items are tuples for two functions. The signatures are different for loader or dumper. The first function returns a boolean, and if the value is true, the object will call the second function and return its result. Basically a loader and a dumper class have no functionality (but come with a default list of handlers). So, to add support for a new type, it is sufficient to write a function that outputs the desired value, and a function that decides when to call that. The index() function returns the position of handlers in the list, so that it is possible to remove them or add new handlers before or after a given handler. The pointer to the loader or dumper object is passed, so that the attributes in use for that particular object are available. For example, if we want to add a special loader that when loading the int 42 into a string returns 'quarantadue', we can do this: from typedload.dataloader import Loader l = Loader() l.handlers.insert( l.index(str), # This will place this entry before the string handler ( lambda x: x == str, lambda loader, value, type_: str(value) if value != 42 else 'quarantadue' ) ) Then this will happen: In [15]: l.load(12, str) Out[15]: '12' In [16]: l.load(42, str) Out[16]: 'quarantadue' This can of course be used also for use cases that make sense. The handlers must generate exceptions from the typedload.exceptions module. Due to internal cache, it is not supported to modify the list of the handlers after the first call to dump/load. Name mangling ============= Name mangling is supported in datatypes with metadata (dataclass, attrs) by having a 'name' key in the metadata. @attr.s class Example: attribute = attr.ib(type=int, metadata={'name': 'att.rib.ute:name'} @dataclass class Example(): attribute: str = field(metadata={'name': 'att.rib.ute:name'}) The dictionary key for 'attribute' will be 'att.rib.ute:name'. This is very useful for keys that use invalid or reserved characters that can't be used in variable names. Another common application is to convert camelCase into not_camel_case. It is implemented this way to avoid doing automatic name translations, that might introduce surprises. To use a metadata key different than 'name', set the mangle_key parameter to the loader/dumper. """ # Copyright (C) 2018-2021 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from typing import Any, Type, TypeVar __all__ = [ 'dataloader', 'load', 'datadumper', 'dump', 'typechecks', ] T = TypeVar('T') def load(value: Any, type_: Type[T], **kwargs) -> T: """ Quick function call to load data into a type. It is useful to avoid creating the Loader object, in case only the default parameters are used. For repeated calls this function will be slower than re-using a loader object. """ from . import dataloader loader = dataloader.Loader(**kwargs) return loader.load(value, type_) def dump(value: Any, **kwargs) -> Any: """ Quick function to dump a data structure into something that is compatible with json or other programs and languages. It is useful to avoid creating the Dumper object, in case only the default parameters are used. """ from . import datadumper dumper = datadumper.Dumper(**kwargs) return dumper.dump(value) typedload/typedload/__init__.pyi0000664000175000017500000000424114721335070016351 0ustar salvosalvo# Copyright (C) 2022 Martin Fischer # Copyright (C) 2023-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli from typing import Set, TypeVar, Type, Any, Optional, Dict, List, Tuple, Callable, _SpecialForm from .dataloader import Loader from .datadumper import Dumper # Load and dump take **kwargs for backwards-compatibility. # This interface file intentionally omits **kwargs so that # typos can be caught by static type checkers. # If you want to extend Loader or Dumper in a type-safe manner # you should subclass them (instead of using **kwargs). __all__ = [ 'dataloader', 'load', 'datadumper', 'dump', 'typechecks', ] T = TypeVar('T') def load( value: Any, type_: Type[T] | _SpecialForm, basictypes: Set[Type[Any]] = ..., basiccast: bool = ..., failonextra: bool = ..., raiseconditionerrors: bool = ..., frefs: Optional[Dict[str, Type[Any]]] = ..., dictequivalence: bool = ..., mangle_key: str = ..., uniondebugconflict: bool = ..., strconstructed: Set[Type[Any]] = ..., handlers: List[ Tuple[Callable[[Any], bool], Callable[[Loader, Any, Type[Any]], Any]] ] = ..., pep563: bool = ..., ) -> T: ... def dump( value: Any, hidedefault: bool = ..., isodates: bool = ..., raiseconditionerrors: bool = ..., mangle_key: str = ..., handlers: List[Tuple[Callable[[Any], bool], Callable[['Dumper', Any, Any], Any]|Callable[['Dumper', Any], Any]]] = ..., strconstructed: Set[Type[Any]] = ..., ) -> Any: ... typedload/typedload/helpers.py0000664000175000017500000000166514721335070016112 0ustar salvosalvo""" typedload Internal helper functions """ # Copyright (C) 2021-2024 Salvo "LtWorf" Tomaselli # # typedload is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . # # author Salvo "LtWorf" Tomaselli __all__ = [ 'tname', ] def tname(type_) -> str: ''' Return a nice string for a type ''' return getattr(type_, '__qualname__', str(type_))