委托未知字典以更正许多数据类的数据类的 Pythonic 方法

Pythonic way to delegate unknown dict to correct dataclasses of many dataclasses

假设我有以下数据类:

@dataclass(frozen=True)
class VisitNotification:
    visit_id: str
    status: str

@dataclass(frozen=True)
class ConversationNotification:
    message_id: str
    status: str

我有软件从队列中提取消息,可以是 {"visit_id": "foo", "status": "bar"}{"message_id": "foo", "status": "bar"}

我想我可以做这样的事情,但感觉很乱,所以我正在寻找一个更 pythonic 和干净的解决方案来将未知类型的消息委托给适当的数据类

try:
    data = VisitNotification(**message)
    return data
except TypeError:
    pass

ConversationNotification(**message)
return data

更多信息

IIUC,因为你正在使用 pydantic,我想这就是你要找的:

from typing import Union

from pydantic.dataclasses import dataclass
from pydantic.tools import parse_obj_as


@dataclass(frozen=True)
class VisitNotification:
    visit_id: str
    status: str


@dataclass(frozen=True)
class ConversationNotification:
    message_id: str
    status: str


T1 = Union[VisitNotification, ConversationNotification]


o1 = parse_obj_as(T1, {"visit_id": "foo", "status": "bar"})
assert type(o1) is VisitNotification

o2 = parse_obj_as(T1, {"message_id": "foo", "status": "bar"})
assert type(o2) is ConversationNotification