Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

code to walk models #4

Open
tlambert03 opened this issue Mar 9, 2023 · 0 comments
Open

code to walk models #4

tlambert03 opened this issue Mar 9, 2023 · 0 comments

Comments

@tlambert03
Copy link

tlambert03 commented Mar 9, 2023

from typing import Iterator, Type, Union, get_origin, get_args
from pydantic import BaseModel


def walk_model(model: Type[BaseModel]) -> Iterator[Type[BaseModel]]:
    for field_name, field in model.__fields__.items():
        if isinstance(field.type_, type) and issubclass(field.type_, BaseModel):
            yield from walk_model(field.type_)
            yield field.type_
        elif get_origin(field.type_) is Union:
            for union_type in get_args(field.type_):
                if isinstance(union_type, type) and issubclass(
                    union_type, BaseModel
                ):
                    yield from walk_model(union_type)
                    yield union_type
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant