[Python] how to import module with TYPE_CHECKING as true

Discussão em 'Python' iniciado por Stack, Agosto 20, 2025.

  1. Stack

    Stack Membro Participativo

    I want to generate a schema based on a class defined in another file, so i need to know the return type of these functions. However, the annotation might be based on some imports under TYPE_CHECKING.

    For example:

    • The class file:

    from typing import TYPE_CHECKING
    if TYPE_CHECKING:
    import xxx
    class RandomClass():
    def random_function(self) -> xxx: ...

    • Then my logic:

    file_module = import_module("random_class_file")
    for func in inspect.getmembers(RandomClass, predicate=inspect.isfunction).values():
    get_type_hints(func, globalns=file_module.__dict__)


    The problem: The logic above will fail because xxx is undefined, as xxx is imported under TYPE_CHECKING. How should I resolve this?

    Continue reading...

Compartilhe esta Página