aiocoap.util.dataclass_data module¶
Tools to load a typed dataclass from CBOR/JSON/TOML/YAML-model data.
Unlike what is in the aiocoap.credentials module, this works from the fixed assumption that the item is a dataclass (as opposed to having an arbitrary constructor), which should ease things.
Caveats:
The module expects the data classes’ annotations to be types and not strings, and therefore can’t be used with types defined under from __future__ import annotations.
While
Optional[str]and other primitives are supported, child load-store classes need to be dressed as| None(i.e., aUnion). This can be simplified when support for Python 3.13 is dropped, as both versions have the typetyping.Unionstarting with Python 3.14.
>>> from dataclasses import dataclass
>>> from typing import Optional
>>> @dataclass
... class Inner(LoadStoreClass):
... some_text: str
... some_number: Optional[int]
>>> @dataclass
... class Top(LoadStoreClass):
... x: str
... y: Inner | None
>>> Top.load({"x": "test", "y": {"some-text": "one", "some-number": 42}})
Top(x='test', y=Inner(some_text='one', some_number=42))
- class aiocoap.util.dataclass_data.LoadStoreClass¶
Bases:
object- classmethod load(data: dict, prefix: str = '', depth_limit: int = 16) Self¶
Creates an instance from the given data dictionary.
Keys are used to populate fields like in the initializer; dashes (“-“) in names are replaced with underscores (“_”) so that Python-idiomatic field names (in snake_case) can be used with TOML idiomatic item names (in kebab-case).
Values are type-checked against the annotations, and unknown fields are disallowed. When annotations indicate another
LoadStoreClass, initialization recurses into that type up to a depth limit.The
prefixis used for error messages: It builds up in the recursive build process and thus gives the user concrete guidance as to where in the top-level item the trouble was. For data loaded from files, it is prudent to give the file name in this argument.This reliably raises
ValueErroror its subtypes on unacceptable data as long as the class is set up in a supported way.