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

Flaky comparison for models with cached properties in version < 2.6 #8274

Closed
1 task done
marcus-idealworks opened this issue Dec 1, 2023 · 1 comment
Closed
1 task done
Assignees
Labels
bug V2 Bug related to Pydantic V2 duplicate

Comments

@marcus-idealworks
Copy link

marcus-idealworks commented Dec 1, 2023

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

The comparison of two objects of a pydantic model with a cached property shows unexpected behavior. The __eq__ operator does not explicitly evaluate cached properties. Therefore, the objects are compared based on previous evaluations. If a cached property was previously evaluated for exactly one of the compared objects, __eq__ results in False.

Expected behavior: If the cached properties have not been evaluated before a call to __eq__, they are evaluated during the comparison.

The issue is already resolved on main due to the changes of BaseModel.__eq__ (

def __eq__(self, other: Any) -> bool:
).

Example Code

from pydantic import BaseModel
from functools import cached_property


class M(BaseModel):
    a: int
    b: int

    @cached_property
    def c(self) -> int:
        return self.a + self.b


m0 = M(a=1, b=2)
m1 = M(a=1, b=2)
m0.c
assert m0 == m1 # failing

Python, Pydantic & OS Version

             pydantic version: 2.5.0
        pydantic-core version: 2.14.1
          pydantic-core build: profile=release pgo=true
                 install path: /home/**/.venv/lib/python3.11/site-packages/pydantic
               python version: 3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801]
                     platform: Linux-6.5.12-1-MANJARO-x86_64-with-glibc2.38
             related packages: typing_extensions-4.8.0 mypy-0.991
@marcus-idealworks marcus-idealworks added bug V2 Bug related to Pydantic V2 pending Awaiting a response / confirmation labels Dec 1, 2023
@sydney-runkle sydney-runkle added duplicate and removed pending Awaiting a response / confirmation labels Dec 1, 2023
@sydney-runkle sydney-runkle self-assigned this Dec 1, 2023
@sydney-runkle
Copy link
Member

Hi @marcus-idealworks,

Thanks for reporting this. @alexmojaki and @QuentinSoubeyranAqemia worked hard to fix this in #7825. This fix will be released with 2.6.0. If you need the fix now, you can pull from main :)

Closing as a dupe of #7444

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

No branches or pull requests

2 participants