Make the Python json encoder support Python's new dataclasses

前端 未结 6 1255
忘掉有多难
忘掉有多难 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:38

    I'd suggest creating a parent class for your dataclasses with a to_json() method:

    import json
    from dataclasses import dataclass, asdict
    
    @dataclass
    class Dataclass:
        def to_json(self) -> str:
            return json.dumps(asdict(self))
    
    @dataclass
    class YourDataclass(Dataclass):
        a: int
        b: int
    
    x = YourDataclass(a=1, b=2)
    x.to_json()  # '{"a": 1, "b": 2}'
    

    This is especially useful if you have other functionality to add to all your dataclasses.

提交回复
热议问题