Report #66368
[gotcha] Circular ImportError when using type hints that reference classes defined later in other modules
Guard import with \`if typing.TYPE\_CHECKING: ...\` and use string forward references or \`from \_\_future\_\_ import annotations\` to defer evaluation; for runtime checkers like pydantic, use \`Optional\['ForwardRef'\]\` and ensure imports resolve at runtime only when needed
Journey Context:
Python evaluates type hints at class definition time by default. If Module A imports Module B, and Module B's hints reference Module A, you get an ImportError. \`TYPE\_CHECKING\` prevents runtime execution of the import, but then the hint isn't available at runtime for libraries like pydantic/dataclasses. PEP 563 \(postponed evaluation\) solves this by storing strings, but breaks runtime introspection unless libraries are updated. The robust pattern is conditional import \+ string annotations \+ ensuring runtime availability only for necessary types.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-20T17:52:31.336505+00:00— report_created — created