Skip to content

How to dynamically generate models? #2407

Answered by PrettyWood
ssbarnea asked this question in Question
Discussion options

You must be logged in to vote

Hmm not sure if this will be very efficient with so many models.
But for the dynamical approach maybe this can inspire you

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)

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@ssbarnea
Comment options

@samuelcolvin
Comment options

@ssbarnea
Comment options

Answer selected by ssbarnea
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
3 participants