python / python/mypy

New semantic analyzer: some assignments aren't recognized as types if incomplete

Open
#6,985 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

false-positive priority-1-normal semantic-analyzer
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

In the following test case the forward reference to In in the class body doesn't work:

[case testNewAnalyzerNamedTupleCallNested]
from typing import NamedTuple
o: C.Out
i: C.In
reveal_type(o)  # E: Revealed type is 'Tuple[Tuple[builtins.str, __main__.C.Other, fallback=__main__.C.In], __main__.C.Other, fallback=__main__.C.Out]'
reveal_type(o.x)  # E: Revealed type is 'Tuple[builtins.str, __main__.C.Other, fallback=__main__.C.In]'
reveal_type(o.y)  # E: Revealed type is '__main__.C.Other'
reveal_type(o.x.t)  # E: Revealed type is '__main__.C.Other'
reveal_type(i.t)  # E: Revealed type is '__main__.C.Other'

class C:
    Out = NamedTuple('Out', [('x', In), ('y', Other)])   # 'In' undefined  <<--- should be ok?
    In = NamedTuple('In', [('s', str), ('t', Other)])
    class Other: pass

The root cause is that if the rvalue of an assignment is incomplete, we add a PlaceholderNode that doesn't have becomes_typeinfo set. This may also affect other things such as assignment-based TypedDicts, type aliases, type variables and NewTypes (haven't checked).

Not sure what would be the best way to fix this. One idea would be to treat every placeholder as a possible type, at least if it's generated from an incomplete assignment. A second idea would be to recognize possible types by looking at an incomplete rvalue, but this doesn't seem always possible.

This is follow-up to #6983.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by running the provided test case for testNewAnalyzerNamedTupleCallNested and inspect how the incomplete assignment creates a PlaceholderNode. Check whether the same behavior affects assignment-based TypedDicts, type aliases, type variables, or NewTypes, as noted in the issue. Done means the forward reference resolves and the listed reveal_type expectations pass without regressing related cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.