Skip to content

Generate a hash function when allow_mutation is False #1880

@rhuille

Description

@rhuille

Feature Request

Output of python -c "import pydantic.utils; print(pydantic.utils.version_info())":

             pydantic version: 1.6.1
            pydantic compiled: False
                 install path: /home/raphael/rhuille/pydantic/pydantic
               python version: 3.8.5 (default, Aug 18 2020, 10:43:36)  [GCC 7.5.0]
                     platform: Linux-5.0.0-1067-oem-osp1-x86_64-with-glibc2.27
     optional deps. installed: ['typing-extensions', 'email-validator', 'devtools']

Hi there,

I need the model to be hashable when I set allow_mutation to False. I could write myself a __hash__ function, but I think it could be nice if pydantic generated it by default in the class BaseModel.

This would be the same behavior of the built-in dataclass which generate a hash function if the object is immutable (parameter frozen is True) and the __eq__ function exists.

Quoting the documentation https://docs.python.org/3/library/dataclasses.html :

If eq and frozen are both true, by default dataclass() will generate a __hash__() method for you.

We could generate a default __hash__ function for BaseModel if allow_mutation is False, what do you think ?

Examples

For example, now we have:

from pydantic import BaseModel

class A(BaseModel):
    x: int
    
    class Config:
        allow_mutation = False

a = A(x=1)
d = {a: 2}

>>> TypeError: unhashable type: 'A'

After, we would have:

from pydantic import BaseModel

class A(BaseModel):
    x: int
    
    class Config:
        allow_mutation = False

a = A(x=1)
d = {a: 2}
d[a]
>>> 2

(Note that if allow_mutation = True, the hash function would be None and the behavior would not be changed)

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions