Skip to content

Fix forward references not resolving in NamedTuple __init__ signatures - #904

Closed
smoltafet wants to merge 1 commit into
mitmproxy:mainfrom
smoltafet:fix/namedtuple-forward-ref-signature
Closed

smoltafet wants to merge 1 commit into
mitmproxy:mainfrom
smoltafet:fix/namedtuple-forward-ref-signature

Conversation

@smoltafet

Copy link
Copy Markdown

Fixes #765.

For a typing.NamedTuple with a forward reference,

from __future__ import annotations
from typing import NamedTuple

class Foo(NamedTuple):
    b: Bar

class Bar:
    pass

pdoc emitted Warn: Error parsing type annotation ForwardRef('Bar') for bug.Foo.__init__. Import of Bar failed: name 'Bar' is not defined, and the parameter type in the constructor signature stayed unresolved — even though the field itself resolved fine and typing.get_type_hints(Foo) has no problem with this code.

The cause: the __new__ that NamedTuple synthesizes is exec'd in a throwaway namedtuple_Foo module, so inspect.getmodule() returns None for it. Function.signature then evaluated the annotations against an empty global namespace (and safe_eval_type's TYPE_CHECKING fallback is skipped entirely when the module is None). Dataclasses don't hit this because their generated __init__ runs in the defining module's globals.

Fix: in Function.signature, if inspect.getmodule() finds no module, fall back to the module being documented (sys.modules[self.modulename]), which is the namespace the class was defined in.

Tests: new test_namedtuple_forward_ref_init_signature in test/test_doc.py builds the example above in a synthetic module and asserts that the __init__ signature resolves b to Bar without warnings (and that the field variable resolves as well). It fails on the unmodified code. Full test suite: the failure set is identical to master in my environment (a number of html snapshot comparisons and the mtime tests fail there too, unrelated to this change).

@smoltafet

Copy link
Copy Markdown
Author

Hi @mhils, could you take a look at this when you have a moment? Happy to fix up anything that needs changing. Thanks!

@smoltafet

Copy link
Copy Markdown
Author

closing this one, no traction. thanks anyway

@smoltafet smoltafet closed this Nov 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Forward references break with NamedTuples

1 participant