0

I am currently implementing operations over Intercom data model using Pydantic.

Lots of Intercom models implements list of objects as below:

"contacts":{
    "type": "contact.list"
    "contacts": [
        Contact1,
        Contact2,
        …
    ]
}

And we have same logic for some other objects lists.

How can I define a dynamic and generic Pydantic base class to manage it ?

I firstly think to:

class BaseList(BaseModel):
    type: str
    ???

    @validator('type')
    def check_type(cls, v):
        assert v.endswith(".list")
        return v

And then usage as below in my parent model:

class ParentModel(BaseModel):
    contacts: BaseList[Contact]

But I don’t know how to manage the dynamic field name and it’s nested associated key.

Thank you for your help !

Regards

JohnDu17
  • 37
  • 1
  • 6
  • Is there any logic to what the key is (the `contacts` part)? Is there a set of possible values, can it be anything as long as it the plural form of what is in `type`? i.e. what rules do you want to validate it against? – MatsLindh Dec 10 '22 at 12:10
  • Hi @MatsLindh, no logic regarding the key : it can be several different values, but will be the same as parent one. Possibly a set of possible values for both parent and nested keys but I would like would be generic Model. I edit the original post with example of ParentModel usage of the BaseList. Thank you – JohnDu17 Dec 12 '22 at 19:50
  • I think you should change focus to looking for a custom **field type**, not a subclass of `BaseModel`. This requires validation, serialisation, and OpenAPI schema support. I get that you have a `list` here, containing multiple values, not actually an `Enum`, but I refer you to this other question because it is similar in that the same support is required, although implemented slightly differently. A solution to this question will probably enable you to write a solution to yours: https://stackoverflow.com/questions/75587442/validate-pydantic-dynamic-float-enum-by-name-with-openapi-description – NeilG Feb 28 '23 at 03:15

1 Answers1

-1
import typing

class Contact(object):    pass


class BaseModel(object): pass


class ContactList(BaseModel):
    type: str
    contacts: typing.List[Contact]

Not sure if it is what you are looking for? typing.List[SomeType]

Mas Zero
  • 503
  • 3
  • 16
  • Thank you, that is a part of the need but I would like to implement the BaseList with dynamic control and use it in parent model as seen in my post. – JohnDu17 Dec 12 '22 at 19:56