File tree Expand file tree Collapse file tree 1 file changed +16
-1
lines changed
Expand file tree Collapse file tree 1 file changed +16
-1
lines changed Original file line number Diff line number Diff line change @@ -590,6 +590,11 @@ def _is_pydantic_serializable(param: inspect.Parameter) -> bool:
590590 if param .annotation == inspect .Parameter .empty :
591591 return True
592592
593+ # Forward references can't be resolved by Pydantic if the type is not
594+ # available at runtime (e.g. inside `if TYPE_CHECKING:`).
595+ if "ForwardRef" in repr (param .annotation ):
596+ return False
597+
593598 if isinstance (param .annotation , str ):
594599 return False
595600
@@ -664,7 +669,17 @@ def _generate_schema(
664669 # it is not JSON serializable. We hence exclude it from the schema.
665670 and param .annotation != asyncio .Queue and _is_pydantic_serializable (param )
666671 }
667- parameters = pydantic .create_model (f .__name__ , ** fields_dict ).schema ()
672+ model = pydantic .create_model (f .__name__ , ** fields_dict )
673+ # Pydantic v2 may not be able to resolve forward references if the
674+ # types are not in the same module. We need to explicitly call
675+ # `model_rebuild` with the correct namespace from the function's module.
676+ # See https://errors.pydantic.dev/2/u/class-not-fully-defined
677+ f_module = inspect .getmodule (f )
678+ if f_module :
679+ model .model_rebuild (
680+ _types_namespace = f_module .__dict__ ,
681+ )
682+ parameters = model .schema ()
668683 # Postprocessing
669684 # 4. Suppress unnecessary title generation:
670685 # * https://github.com/pydantic/pydantic/issues/1051
You can’t perform that action at this time.
0 commit comments