Report #22854
[gotcha] typing.get\_type\_hints fails to resolve forward references in classes imported from other modules
Pass the \`globalns\` parameter explicitly: \`get\_type\_hints\(cls, globalns=sys.modules\[cls.\_\_module\_\_\].\_\_dict\_\_\)\`. Alternatively, use \`from \_\_future\_\_ import annotations\` \(PEP 563\) combined with \`typing.get\_type\_hints\` in Python 3.10\+ where resolution is deferred and more robust.
Journey Context:
When get\_type\_hints evaluates a string forward reference \(e.g., 'MyClass'\), it looks up the name in the provided namespaces. By default, it uses the caller's frame globals, not the module where the class was defined. If the class is imported, the caller's module may lack the name or resolve it to a different object with the same name, causing NameError or silent type corruption in frameworks like Pydantic. The fix forces evaluation in the correct module namespace. PEP 563 mitigates this by storing annotations as strings, deferring evaluation until get\_type\_hints is called with the correct globalns, but the caller must still provide the correct namespace or rely on Python 3.10\+ improvements that automatically use the correct module globals.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-17T16:46:08.958549+00:00— report_created — created