Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The hash magic method of the stdlib dataclasses disappears on conversion to pydantic dataclasses #2383

Closed
3 tasks done
Dementiy opened this issue Feb 21, 2021 · 3 comments · Fixed by #2557
Closed
3 tasks done
Labels
bug V1 Bug related to Pydantic V1.X

Comments

@Dementiy
Copy link

Checks

  • I added a descriptive title to this issue
  • I have searched (google, github) for similar issues and couldn't find anything
  • I have read and followed the docs and still think this is a bug

Bug

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

             pydantic version: 1.7.3
            pydantic compiled: True
                 install path: /Users/dementiy/.virtualenvs/test-env/lib/python3.8/site-packages/pydantic
               python version: 3.8.5 (default, Jul 21 2020, 10:48:26)  [Clang 11.0.3 (clang-1103.0.32.62)]
                     platform: macOS-10.15.1-x86_64-i386-64bit
     optional deps. installed: ['typing-extensions']

Here is minimal example illustrated the problem:

import dataclasses
import pydantic


@dataclasses.dataclass
class A:
    s: str

    def __hash__(self):
       return 123

class B(pydantic.BaseModel):
    a: A


def test_unhashable():
    a = A("")
    b = B(a=a)

    assert hash(a) == 123

    with pytest.raises(TypeError) as e:
        assert hash(b.a) == 123
    assert "unhashable type" in str(e.value)
@Dementiy Dementiy added the bug V1 Bug related to Pydantic V1.X label Feb 21, 2021
@PrettyWood
Copy link
Member

Hi @Dementiy and thanks for reporting!
Well we could copy __hash__ here
https://github.com/samuelcolvin/pydantic/blob/b7a8ef25c667b5dd4c4cd0b109c6625d1a57139a/pydantic/dataclasses.py#L132-L133
but I feel like the issue should be put in perspective with #2182.
The main thing is "how different should the pydantic dataclass (with validation) be compared to the stdlib one?"

@Dementiy
Copy link
Author

I think that adding __hash__ doesn't break anything (the same for __eq__) and also we get the expected behavior. Should I create a pull request?

@PrettyWood
Copy link
Member

Hi @Dementiy
FYI I started to work again on the whole stdlib dataclass to validated dataclass #2557. Feedback more than welcome! 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug V1 Bug related to Pydantic V1.X
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants