Make the Python json encoder support Python's new dataclasses

前端 未结 6 1254
忘掉有多难
忘掉有多难 2021-02-03 16:59

Starting with Python 3.7, there is something called a dataclass:

from dataclasses import dataclass

@dataclass
class Foo:
    x: str

However, t

6条回答
  •  执念已碎
    2021-02-03 17:44

    A much simpler answer can be found on Reddit using dictionary unpacking

    >>> from dataclasses import dataclass
    >>> @dataclass
    ... class MyData:
    ...   prop1: int
    ...   prop2: str
    ...   prop3: int
    ...
    >>> d = {'prop1': 5, 'prop2': 'hi', 'prop3': 100}
    >>> my_data = MyData(**d)
    >>> my_data
    MyData(prop1=5, prop2='hi', prop3=100)
    

提交回复
热议问题