Pydantic: Nested basemodel contain different instances of child models in a collection than origially provided.

Created on 16 Aug 2020  路  2Comments  路  Source: samuelcolvin/pydantic

Question

I wanted to use an ID based hashing for BaseModel instances. It appears to be the case that nested base models create new objects in a hashable collection like set or a mutable collection like List.

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

           pydantic version: 1.6.1
           pydantic compiled: True
           install path: /home/umesh/personal/pydantic/pydantic
           python version: 3.7.8 | packaged by conda-forge | (default, Jul 31 2020, 02:25:08)  [GCC 7.5.0]
           platform: Linux-5.0.0-32-generic-x86_64-with-debian-buster-sid
           optional deps. installed: ['typing-extensions', 'email-validator', 'devtools']

In this snippet (grabbed from FastAPI examples). Class Item has a list of Images, which adhere to equality based on id. It appears to be the case that instance variable images of Item contain images are different from the ones originally provided from the constructor. Is there a way to skirt that?

from pydantic import BaseModel
from typing import List, Set, Optional


class Image(BaseModel):
    url: str
    name: str

    def __hash__(self):
        return id(self)

    def __eq__(self, other):
        return self is other


class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
    tags: Set[str] = []
    images: Optional[List[Image]] = None


image_1 = Image(url='https://s3.amazon-aws.com/dakl/kals', name='profile_pic_1.png')
image_2 = Image(url='https://s3.amazon-aws.com/dakl/kals', name='profile_pic_1.png')

item = Item(name='my_item1', price=0.050, images={image_1, image_2})
print(image_1 in item.images)

print(id(image_1), id(item.images[0]), id(image_2), id(item.images[1]))

Output:

139644562343408 139644562344208 139644562343328 139644562344368
question

Most helpful comment

Hello @umesh-timalsina
This is a known "issue", which may or may not be changed in v2. It reminds me of #265, which could help you. I'm currently not with my computer sorry

All 2 comments

Hello @umesh-timalsina
This is a known "issue", which may or may not be changed in v2. It reminds me of #265, which could help you. I'm currently not with my computer sorry

Hello @PrettyWood. Thanks for the response. I will check the issue out.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dmontagu picture dmontagu  路  3Comments

nav picture nav  路  3Comments

mgresko picture mgresko  路  3Comments

cdeil picture cdeil  路  3Comments

engstrom picture engstrom  路  3Comments