Search code examples
pythonattributespython-attrs

How to achieve the reverse of "attr.asdict(MyObject)" using Python module 'attrs'


In documentation of Python module attrs stated that there is a method to convert attributes’ class into dictionary representation:

Example:

>>> @attr.s
... class Coordinates(object):
...     x = attr.ib()
...     y = attr.ib()
...
>>> attr.asdict(Coordinates(x=1, y=2))
{'x': 1, 'y': 2}

How can I achieve the opposite, instantiating the Coordinates from its valid dictionary representation without boilerplate and with the joy of the attrs module?


Solution

  • Apparently as easy as using dictionary unpacking (double star) operator in corresponding attrs class instantiation.

    Example:

    >>> Coordinates(**{'x': 1, 'y': 2})
    Coordinates(x=1, y=2)