How to solve multiple and nested discriminators with Pydantic v2?

I am trying to validate Slack interaction payloads, that look like these:

type: block_actions
container:
  type: view
...
type: block_actions
container:
  type: message
...
type: view_submission
...

I use 3 different models for payloads coming to the same interaction endpoint:

class MessageContainer(BaseModel):
    type: Literal["message"]
    ...

class ViewContainer(BaseModel):
    type: Literal["view"]
    ...

class MessageActions(ActionsBase):
    type: Literal["block_actions"]
    container: MessageContainer
    ...

class ViewActions(ActionsBase):
    type: Literal["block_actions"]
    container: ViewContainer
    ...

class ViewSubmission(BaseModel):
    type: Literal["view_submission"]
    ...

and I was planning to use

BlockActions = Annotated[
    MessageActions | ViewActions,
    Field(discriminator="container.type"),
]
SlackInteraction = Annotated[
    ViewSubmission | BlockActions,
    Field(discriminator="type"),
]
SlackInteractionAdapter = TypeAdapter(SlackInteraction)

but cannot make it work with v2.10.4.

Do I have to dispatch them manually or there is a way to solve it with Pydantic?

Not sure it’s possible to use 2 discriminators to resolve one type (as you are trying to do).

I can suggest you 3 options:

1. Split block_actions into block_message_actions and block_view_actions:

from typing import Annotated, Literal

from pydantic import BaseModel, Field, TypeAdapter


class MessageContainer(BaseModel):
    pass

class ViewContainer(BaseModel):
    pass


class ActionsBase(BaseModel):
    pass

class MessageActions(ActionsBase):
    type: Literal["block_message_actions"]
    container: MessageContainer


class ViewActions(ActionsBase):
    type: Literal["block_view_actions"]
    container: ViewContainer


class ViewSubmission(BaseModel):
    type: Literal["view_submission"]


SlackInteraction = Annotated[
    ViewSubmission | ViewActions | MessageActions,
    Field(discriminator="type"),
]

SlackInteractionAdapter = TypeAdapter(SlackInteraction)



a = SlackInteractionAdapter.validate_python({"type": "view_submission"})
assert isinstance(a, ViewSubmission)


b = SlackInteractionAdapter.validate_python(
    {"type": "block_message_actions", "container": {}},
)
assert isinstance(b, MessageActions)
assert isinstance(b.container, MessageContainer)


c = SlackInteractionAdapter.validate_python(
    {"type": "block_view_actions", "container": {}},
)
assert isinstance(c, ViewActions)
assert isinstance(c.container, ViewContainer)

2. Use Discriminated Unions with callable Discriminator:


def get_discriminator_value(v: Any) -> str:
    if isinstance(v, dict):
        if v["type"] == "view_submission":
            return "view_submission"
        return "message_action" if v["container"]["type"] == "message" else "view_action"
    if v.type == "view_submission":
        return "view_submission"
    return "message_action" if v.container.type == "message" else "view_action"


SlackInteraction = Annotated[
    Union[
        Annotated[ViewSubmission, Tag("view_submission")],
        Annotated[MessageActions, Tag("message_action")],
        Annotated[ViewActions, Tag("view_action")],
    ],
    Discriminator(get_discriminator_value),
]
SlackInteractionAdapter = TypeAdapter(SlackInteraction)

3. Use nested discriminated unions:

from typing import Annotated, Literal

from pydantic import BaseModel, Field, TypeAdapter


class MessageContainer(BaseModel):
    type: Literal["message"]

class ViewContainer(BaseModel):
    type: Literal["view"]


ActionContainer = Annotated[
    MessageContainer | ViewContainer,
    Field(discriminator="type"),
]

class BlockActions(BaseModel):
    type: Literal["block_actions"]
    container: ActionContainer



class ViewSubmission(BaseModel):
    type: Literal["view_submission"]



SlackInteraction = Annotated[
    ViewSubmission | BlockActions,
    Field(discriminator="type"),
]

SlackInteractionAdapter = TypeAdapter(SlackInteraction)


a = SlackInteractionAdapter.validate_python({"type": "view_submission"})
assert isinstance(a, ViewSubmission)


b = SlackInteractionAdapter.validate_python(
    {"type": "block_actions", "container": {"type": "message"}},
)
assert isinstance(b, BlockActions)
assert isinstance(b.container, MessageContainer)


c = SlackInteractionAdapter.validate_python(
    {"type": "block_actions", "container": {"type": "view"}},
)
assert isinstance(c, BlockActions)
assert isinstance(c.container, ViewContainer)

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa

How to solve multiple and nested discriminators with Pydantic v2?

I am trying to validate Slack interaction payloads, that look like these:

type: block_actions
container:
  type: view
...
type: block_actions
container:
  type: message
...
type: view_submission
...

I use 3 different models for payloads coming to the same interaction endpoint:

class MessageContainer(BaseModel):
    type: Literal["message"]
    ...

class ViewContainer(BaseModel):
    type: Literal["view"]
    ...

class MessageActions(ActionsBase):
    type: Literal["block_actions"]
    container: MessageContainer
    ...

class ViewActions(ActionsBase):
    type: Literal["block_actions"]
    container: ViewContainer
    ...

class ViewSubmission(BaseModel):
    type: Literal["view_submission"]
    ...

and I was planning to use

BlockActions = Annotated[
    MessageActions | ViewActions,
    Field(discriminator="container.type"),
]
SlackInteraction = Annotated[
    ViewSubmission | BlockActions,
    Field(discriminator="type"),
]
SlackInteractionAdapter = TypeAdapter(SlackInteraction)

but cannot make it work with v2.10.4.

Do I have to dispatch them manually or there is a way to solve it with Pydantic?

Not sure it’s possible to use 2 discriminators to resolve one type (as you are trying to do).

I can suggest you 3 options:

1. Split block_actions into block_message_actions and block_view_actions:

from typing import Annotated, Literal

from pydantic import BaseModel, Field, TypeAdapter


class MessageContainer(BaseModel):
    pass

class ViewContainer(BaseModel):
    pass


class ActionsBase(BaseModel):
    pass

class MessageActions(ActionsBase):
    type: Literal["block_message_actions"]
    container: MessageContainer


class ViewActions(ActionsBase):
    type: Literal["block_view_actions"]
    container: ViewContainer


class ViewSubmission(BaseModel):
    type: Literal["view_submission"]


SlackInteraction = Annotated[
    ViewSubmission | ViewActions | MessageActions,
    Field(discriminator="type"),
]

SlackInteractionAdapter = TypeAdapter(SlackInteraction)



a = SlackInteractionAdapter.validate_python({"type": "view_submission"})
assert isinstance(a, ViewSubmission)


b = SlackInteractionAdapter.validate_python(
    {"type": "block_message_actions", "container": {}},
)
assert isinstance(b, MessageActions)
assert isinstance(b.container, MessageContainer)


c = SlackInteractionAdapter.validate_python(
    {"type": "block_view_actions", "container": {}},
)
assert isinstance(c, ViewActions)
assert isinstance(c.container, ViewContainer)

2. Use Discriminated Unions with callable Discriminator:


def get_discriminator_value(v: Any) -> str:
    if isinstance(v, dict):
        if v["type"] == "view_submission":
            return "view_submission"
        return "message_action" if v["container"]["type"] == "message" else "view_action"
    if v.type == "view_submission":
        return "view_submission"
    return "message_action" if v.container.type == "message" else "view_action"


SlackInteraction = Annotated[
    Union[
        Annotated[ViewSubmission, Tag("view_submission")],
        Annotated[MessageActions, Tag("message_action")],
        Annotated[ViewActions, Tag("view_action")],
    ],
    Discriminator(get_discriminator_value),
]
SlackInteractionAdapter = TypeAdapter(SlackInteraction)

3. Use nested discriminated unions:

from typing import Annotated, Literal

from pydantic import BaseModel, Field, TypeAdapter


class MessageContainer(BaseModel):
    type: Literal["message"]

class ViewContainer(BaseModel):
    type: Literal["view"]


ActionContainer = Annotated[
    MessageContainer | ViewContainer,
    Field(discriminator="type"),
]

class BlockActions(BaseModel):
    type: Literal["block_actions"]
    container: ActionContainer



class ViewSubmission(BaseModel):
    type: Literal["view_submission"]



SlackInteraction = Annotated[
    ViewSubmission | BlockActions,
    Field(discriminator="type"),
]

SlackInteractionAdapter = TypeAdapter(SlackInteraction)


a = SlackInteractionAdapter.validate_python({"type": "view_submission"})
assert isinstance(a, ViewSubmission)


b = SlackInteractionAdapter.validate_python(
    {"type": "block_actions", "container": {"type": "message"}},
)
assert isinstance(b, BlockActions)
assert isinstance(b.container, MessageContainer)


c = SlackInteractionAdapter.validate_python(
    {"type": "block_actions", "container": {"type": "view"}},
)
assert isinstance(c, BlockActions)
assert isinstance(c.container, ViewContainer)

3

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật