Skip to content
This repository was archived by the owner on Sep 14, 2025. It is now read-only.
This repository was archived by the owner on Sep 14, 2025. It is now read-only.

code to walk models #4

Description

@tlambert03
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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions