[Python] Is an instance my Pydantic model in my Enum?

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

  1. Stack

    Stack Membro Participativo

    In my situation I get a response from an API which follows the structure of MyGenericModel. After I parse the response using MyGenericModel, I want to check if it belongs to my set defined in MyEnum. If it does I want to continue with it, if not.. then we proceed further.

    Ideally I would call MyGenericModel(value_one="a", value_two="b") in MyEnum, but this results in a TypeError: unhashable type MyGenericModel

    here is a small simplified example of my code:

    from pydantic import BaseModel
    from enum import Enum


    class MyGenericModel(BaseModel):
    value_one: str
    value_two: str

    def __eq__(self, other):
    return self.model_dump() == other.model_dump()

    def __hash__(self):
    return hash((type(self),) + tuple(self.__dict__.values()))


    class MySpecificModel(MyGenericModel):
    value_one: str = "a"
    value_two: str = "b"


    class MyEnum(Enum):
    my_model = MySpecificModel()


    # This is true
    MyGenericModel(value_one="a", value_two="b") == MySpecificModel()

    # This fails - and I want to be true
    MyGenericModel(value_one="a", value_two="b") in MyEnum



    How can I make this work? Is my current solution too complicated?

    Continue reading...

Compartilhe esta Página