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.
Example use¶
>>> 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 | bytes
... y: Optional[Inner]
... z: dict[str, int]
>>> Top.load({"x": "test", "y": {"some-text": "one", "some-number": 42}, "z": {"a": 1}})
Top(x='test', y=Inner(some_text='one', some_number=42), z={'a': 1})
Stability¶
This module’s content is not stable for direct use.
Nonetheless, it is updated carefully, as changes in behavior of the aiocoap.config module might result from changes here.
Components¶
- class aiocoap.util.dataclass_data.LoadStoreClass¶
Bases:
object- classmethod load(data: dict, *, depth_limit: int = 16, basefile: Path | None = None, _prefix: str | None = None) 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
basefileis used for error messages, and to constructPathitems as relative to the file name given there. (For example, ifbasefile=Path("config.d/test.json"), a value of"test2.json"will be represented asPath("config.d/test2.json")). It also serves as a starting point for the error location indication, which is built into_prefixin recursion as a vague path-like expression liketest.json key/key[key].This reliably raises
ValueErroror its subtypes on unacceptable data as long as the class is set up in a supported way.
- classmethod load_from_file(file: Path | str) Self¶
Loads an item from a file.
The file is opened, and the file type is determined from the extension. The set of supported file types may vary by installed packages and Python version.