How to dynamically generate models? #2407
-
I need to generate a very long list of models programately and add them to the root element of the of the TasksModel I am trying to build: class TasksFileModel(BaseModel):
__root__: List[Union[TaskModel, BlockModel]]
# this allows now two models previous defined, but I need to dynamically create and add ~5000 others
# how can I do this?
class Config:
extra = Extra.forbid
title = "Tasks Schema" |
Beta Was this translation helpful? Give feedback.
Answered by
PrettyWood
Feb 25, 2021
Replies: 1 comment 3 replies
-
Hmm not sure if this will be very efficient with so many models. import string
from typing import Union
from pydantic import BaseModel, create_model, ValidationError
all_models = {
c: create_model(f'Model{c}', **{c: (str, ...)})
for c in string.ascii_lowercase
}
class M(BaseModel):
__root__: Union[tuple(all_models.values())]
M.parse_obj({'a': 'foo'})
M.parse_obj({'b': 'foo'})
try:
M.parse_obj({'aa': 'foo'})
except ValidationError as e:
print(e) |
Beta Was this translation helpful? Give feedback.
3 replies
Answer selected by
ssbarnea
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hmm not sure if this will be very efficient with so many models.
But for the dynamical approach maybe this can inspire you