Skip to content

fix(types): resolve forward-reference return annotations via get_type_hints#1350

Open
devteamaegis wants to merge 2 commits into
PrefectHQ:mainfrom
devteamaegis:fix/from-future-annotations-return-type-950
Open

fix(types): resolve forward-reference return annotations via get_type_hints#1350
devteamaegis wants to merge 2 commits into
PrefectHQ:mainfrom
devteamaegis:fix/from-future-annotations-return-type-950

Conversation

@devteamaegis

Copy link
Copy Markdown

Summary

Closes #950

When a module uses from __future__ import annotations (PEP 563), all annotations are stored as lazy strings at runtime. inspect.signature().return_annotation therefore returns the raw string (e.g. 'Recipe') rather than the actual class. This meant PythonFunction.from_function stored 'Recipe' (a string) as return_annotation, which broke any downstream code that tried to construct a Pydantic schema from it.

Root cause: inspect.signature() preserves the string literal as-is under PEP 563. Only typing.get_type_hints() resolves the forward reference back to the real type.

Fix

In PythonFunction.from_function, replace:

"return_annotation": sig.return_annotation,

with a get_type_hints() call that resolves the annotation, falling back to sig.return_annotation if resolution fails (e.g. the type is not importable in the current scope):

try:
    hints = get_type_hints(func)
    resolved_return = hints.get("return", sig.return_annotation)
except Exception:
    resolved_return = sig.return_annotation

Tests

Two regression tests added in tests/basic/utilities/test_types.py::TestPythonFunctionFromFutureAnnotations:

  • test_string_annotation_is_resolved_to_type — string annotation -> "Dish" must resolve to the Dish class
  • test_non_string_annotation_still_works — normal -> list[Ingredient] must continue to work unchanged

@github-actions github-actions Bot added the tests label May 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

from __future__ import annotations causes ai functions to return strings

1 participant