Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to add a pydantic model to a set gives unhashable error

I have the following code

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = "Jane Doe"


def add_user(user: User):
    a = set()
    a.add(user)
    return a


add_user(User(id=1))

When I run this, I get the following error:

TypeError: unhashable type: 'User'

Is there a way this issue can be solved?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You just need to implement an hash function for the class.
You can easily do that by hashing the User’s id or name and return it as the hash…

like this:

from pydantic import BaseModel


class User(BaseModel):
    id: int
    name = "Jane Doe"

    def __hash__(self) -> int:
        return self.name.__hash__() # or self.id.__hash__()


def add_user(user: User):
    a = set()
    a.add(user)
    return a


add_user(User(id=1))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading