Skip to content

Add flag to avoid imports inside TYPE_CHECKING blocks for pydantic #3038

@Gara-Dorta

Description

@Gara-Dorta

Is your feature request related to a problem?

It looks like there is no option to generate pydantic classes with imports outside the TYPE_CHECK block. For example in #3037, the json schema there, generates classes like this one

from __future__ import annotations

from typing import TYPE_CHECKING

from pydantic import BaseModel, Field

if TYPE_CHECKING:
    from .sync_data_message_schema import SyncDataMessage

class SyncMessage(BaseModel):
    sent_message: SyncDataMessage | None

This means that I need to run SyncMessage.model_rebuild() to be able to use the SyncMessage model. This is okay for a few classes but as in the issue linked above, I have an api with many classes.

Describe the solution you'd like

Either of:

  • A flag to enable generating Model.model_rebuild() in the __init__.py file.
  • A flag to disable the imports inside the TYPE_CHECKING block, so they get imported normally

Describe alternatives you've considered

I considered importing all classes and running model_rebuild in a for loop but that is not readable.

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions