2

in V1 I was able to recursively add information to the BaseModel.dict method. Is something similar possible in V2?

In V1 this was possible:

from typing import Optional

from pydantic.v1 import BaseModel


class BaseModel2(BaseModel):
    def dict(self, **kwargs):
        _dict = super().dict(**kwargs)
        _dict["__name__"] = self.__class__.__name__
        return _dict


class Foo(BaseModel2):
    whatever: int


class Bar(BaseModel2):
    whenever: Optional[float] = 1.1
    foo: Foo


m = Bar(whenever=3.14, foo=Foo(whatever=123))
print(m.dict())

As a result, the dictionary would contain a __name__ for both models, as dict was called recursively.

1 Answer 1

2

You could do this:

from typing import Optional

from pydantic import BaseModel, computed_field


class BaseModel2(BaseModel):

    @computed_field(alias="__name__")
    @property
    def name(self) -> str:
        return self.__class__.__name__


class Foo(BaseModel2):
    whatever: int


class Bar(BaseModel2):
    whenever: Optional[float] = 1.1
    foo: Foo


m = Bar(whenever=3.14, foo=Foo(whatever=123))
print(m.model_dump(by_alias=True))
Sign up to request clarification or add additional context in comments.

2 Comments

This is a great suggestion, let me play a bit with it, and then I think I will accept this as answer!
Do you think there is an alternative way that does not define a new field that would get serialized all the time. What I was able to achieve with the V1 solution (not shown) is to define a contextmanager, that would only call the additional logic when requested, so that normal serialization would still be unaffected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.