microsoft / microsoft/pyright

False positive: `TypeVar`s in functional-style`TypedDicts` are allowed but unsupported

Open
#11,063 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
15.6k
Forks
1.8k
Avg merge
12h 13m
Merged PRs (30d)
52

Description

Describe the bug
Pyright currently allows users to define a TypedDict with functional syntax that contains pre-PEP-695 TypeVars; however, the resulting type cannot be subscripted.

I believe the correct behaviour would be to emit an error at the definition location, informing the user that TypeVars in that context are meaningless.

On a side note, is it currently possible to define a TypedDict that is generic over the type of a key that would not be a valid Python identifier?

Code or Screenshots

from typing import TypedDict, Generic, TypeVar

_T = TypeVar("_T")

# --- class syntax --- #

class Foo(TypedDict, Generic[_T]):   # Generic class-style TypedDicts are supported
    key: _T

def foo(x: Foo[int]):
    reveal_type(x["key"])   # 'int'

# --- functional syntax --- #

Bar = TypedDict("Bar", { "@key": _T })   # no error here

def bar(x: Bar[int]):       # error: 'Bar' does not accept type arguments
    reveal_type(x["@key"])  # '_T@Bar'

(pyright playground)

VS Code extension or command-line
I encountered this problem with the basedpyright VS Code extension, but I can confirm the pyright playground (v1.1.407) exibits the same behaviour.

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 reproducing the functional-style TypedDict example in the linked Pyright playground, focusing on the accepted _T in TypedDict("Bar", {"@key": _T}). Trace the functional TypedDict validation and generic-subscript handling. Done means the definition reports that the TypeVar is unsupported or meaningless, with behavior covered by a regression test; the question about non-identifier keys may need separate investigation.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.