I am new to dataclasses/Pydantic models and I am running into an issue elaborated below.
I have defined two pydantic models
Role
s and SubRole
s such that Role
model contains a set
of SubRole
s.
"""
Module contains all the models.
"""
# pylint: disable=too-few-public-methods
import typing
import pydantic
class RoleBaseClass(pydantic.BaseModel): # pylint: disable=no-member
"""
Base class for all the models.
"""
name: str = pydantic.Field(regex=r"^\w+$")
def __hash__(self: typing.Self) -> int:
return hash(self.name)
def __eq__(self, other) -> bool:
return self.name == other.name
class SubRole(RoleBaseClass):
"""
SubRole model.
"""
class Role(RoleBaseClass):
"""
Role model.
"""
subroles: set[SubRole] = pydantic.Field(default=set())
def __str__(self) -> str:
base_str: str = super().__str__()
cls_name: str = self.__class__.__name__
return f"{cls_name}({base_str})"
if __name__ == "__main__":
data0 = Role(
name="aws0",
)
data1 = Role(
name="aws1",
subroles=set(
[
SubRole(name="aws1sub1"),
SubRole(name="aws1sub2"),
]
),
)
data2 = Role(
name="aws1",
subroles=set(
[
SubRole(name="aws2sub1"),
SubRole(name="aws2sub2"),
]
),
)
print(data0)
print(data1.subroles)
print(data1 == data2)
# Below line fails with TypeError: unhashable type: 'dict'
print(data2.dict())
everything works apart from calling Role().dict()
method which fails with TypeError: unhashable type: 'dict'
error, traceback
below
Traceback (most recent call last):
File "models.py", line 72, in <module>
print(data2.dict())
^^^^^^^^^^^^
File "pydantic\main.py", line 449, in pydantic.main.BaseModel.dict
File "pydantic\main.py", line 868, in _iter
File "pydantic\main.py", line 794, in pydantic.main.BaseModel._get_value
TypeError: unhashable type: 'dict'
Could anyone suggest the mistake I made, also any further improvement to the code.
Cheers, DD.