0

everyone.
Got a problem here.
I have some Pydantic model with some attrs and 99 % of the time I want it that way. But for the remaining 1 % at a time I want it to have some additional attribute.

I can set it dynamically using an extra attribute with the Config object and it works fine except the one thing: Pydantic knows nothing about that attr. So when I want to modify my model back by passing response via FastAPI, it will not be converted to Pydantic model completely (this attr would be a simple dict) and this isn't convenient.

Other possible options:

  1. Just define another model with that attr. I don't consider it as I want to modify Pydantic model itself, converting to dict back and forth inefficient, model is nested and huge.
  2. Make attr Optional. Schema will have it with None and it'll be passed everywhere. Not optimal, because as I said, model in general doesn't need this attribute.

So what I want is:
Maybe it's possible for Pydantic to specify that dynamically can be set attribute of specific type for this model (because I don't have stochastic mutation, I definitely know what would be added), but the general instance of that class will not have it anywhere. And when I set it, Pydantic will handle new structure of my model and will not have any problem with that. I couldn't find anything similar by myself.

Thanks in advance. Would be glad for any help.
P.S. I hope I explained myself very clearly and the code is unnecessary as problem's very straightforward.

  • I'd define a model with all expected attributes with some of those being optional. I think this is a safer way of doing things. – NotAName Aug 25 '23 at 01:39
  • Please take a look at [this](https://stackoverflow.com/a/76131296/17865804) – Chris Aug 25 '23 at 10:16
  • If the behavior of your router with or without this attr doesn't change you can make it optional but if not i would suggest to create a new class that inheritat from your model, to have a better readability – Bastien B Aug 28 '23 at 09:27

0 Answers0