Dictable

class privex.helpers.collections.Dictable[source]

A small abstract class for use with Python 3.7 dataclasses.

Allows dataclasses to be converted into a dict using the standard dict() function:

>>> @dataclass
>>> class SomeData(Dictable):
...     a: str
...     b: int
...
>>> mydata = SomeData(a='test', b=2)
>>> dict(mydata)
{'a': 'test', 'b': 2}

Also allows creating dataclasses from arbitrary dictionaries, while ignoring any extraneous dict keys.

If you create a dataclass using a dict and you have keys in your dict that don’t exist in the dataclass, it’ll generally throw an error due to non-existent kwargs:

>>> mydict = dict(a='test', b=2, c='hello')
>>> sd = SomeData(**mydict)
TypeError: __init__() got an unexpected keyword argument 'c'

Using from_dict you can simply trim off any extraneous dict keys:

>>> sd = SomeData.from_dict(**mydict)
>>> sd.a, sd.b
('test', 2)
>>> sd.c
AttributeError: 'SomeData' object has no attribute 'c'
__init__()

Initialize self. See help(type(self)) for accurate signature.

Methods

Methods

from_dict(env)