[Python] Defining a type that is both a Protocol and a Pydantic BaseModel

Discussão em 'Python' iniciado por Stack, Maio 20, 2025.

  1. Stack

    Stack Membro Participativo

    I need to define a type that is both a Protocol and a BaseModel.

    In detail:
    The model Foo has a field data that can receive any model that has an id attribute ( let's call the type HasId).

    class Foo(BaseModel):
    data: HasId
    ...


    If Protocol supported inheriting from other base classes I would have defined HasId like this:

    class HasId(BaseModel, Protocol):
    id: str | UUID


    Or using the Intersection solution proposed here here I would have define it like this:

    class HasIdProtocol(Protocol):
    id: str | UUID

    type HasId = Intersection[HasIdProtocol, BaseModel]
    # OR
    type HasId = HasIdProtocol & BaseModel



    Is there a way I can still achieve this functionality currently?

    Continue reading...

Compartilhe esta Página