Search code examples
pythonpython-3.xpydantic

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?


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))