2

I am currently working with following nested model (FinalModel):

class Model1(BaseModel):
    count: int

class Model2(BaseModel):
    method: str
    selector: dict
    count: int

class FinalModel(BaseModel):
    slow: bool
    models: Tuple[
        Optional[Model1],
        Optional[Model2],
    ]]

I am expecting the Tuple to have a variable length since I'd like to pass in either Model1 or Model2 or both based on the requirements. However, the tuple seems to be expecting a fixed length of 2.

Please note that Union is not an option for me since I expect number of models to increase in future and the possible combinations will increase as well.

2 Answers 2

2

To specify a variable-length tuple of multiple types you can use ellipsis literal ... and Union, like below:

class FinalModel(BaseModel):
    slow: bool
    models: Tuple[Union[Model2, Model1], ...]

When using Union one also need to keep in mind that:

However, as can be seen above, pydantic will attempt to 'match' any of the types defined under Union and will use the first one that matches.[...]

As such, it is recommended that, when defining Union annotations, the most specific type is included first and followed by less specific types.

Therefore, for your example, Model2 must precede Model1 in Union, since the objects of Model2 when parsing will match with Model1, and the other members will be discarded. Or use extra = forbid.

class Model1(BaseModel):
    count: int

    class Config:
        extra = "forbid"
Sign up to request clarification or add additional context in comments.

Comments

1

Are you sure you want to use a tuple? A tuple is fixed size in its nature, using it in you Pydantic model will require both elements to be present.

Instead, you could use a List[Union[Model1, Model2]]

1 Comment

That works as well. I ended up using Tuple itself. As suggested by Eric Jolibois on github, Tuple[Union[Model1, Model2],...]

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.