[Python] How to specify actual class in Pydantic member

Discussão em 'Python' iniciado por Stack, Março 22, 2025.

  1. Stack

    Stack Membro Participativo

    I'd like to serialize and deserialize an object holding a polymorphic member.

    If the class was polymorphic, I would use a correct concrete type with TypeAdapter. The question is, how to do the same when a member is polymorphic. Here's a minimal example of what I mean:

    from abc import ABC, abstractmethod
    from pydantic import BaseModel, TypeAdapter


    class I_Widget(ABC, BaseModel):
    @abstractmethod
    def do_stuff(self): ...


    class WidgetHolder(BaseModel):
    widget: I_Widget


    class ActualWidget(I_Widget):
    value: int

    def do_stuff(self):
    print('Doing stuff')


    if __name__ == '__main__':
    w = ActualWidget(value=42)
    wh = WidgetHolder(widget=w)

    # Serializes:
    json = wh.json()

    # Deserializes:
    wh2 = TypeAdapter(WidgetHolder).validate_json(json) # Throws an error


    When I run it, I get:

    File "/home/adam/.cache/pypoetry/virtualenvs/poc-py3.12/lib/python3.12/site-packages/pydantic/type_adapter.py", line 446, in validate_json
    return self.validator.validate_json(
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: Can't instantiate abstract class I_Widget without an implementation for abstract method 'do_stuff'

    Continue reading...

Compartilhe esta Página