pyrefly icon indicating copy to clipboard operation
pyrefly copied to clipboard

Generics usage for a TypedDict's extra_items breaks type checking

Open gbelouze opened this issue 2 months ago • 2 comments

Describe the Bug

The simplest example would be

from typing import TypedDict

class TD[T](TypedDict, extra_items=T):
    a: int

d: TD[str] = {"a":1}
reveal_type(d2["b"])  # T  # expected str

but also

# ERROR sandbox.py:19:28-31: `Literal['b']` is not assignable to TypedDict key with type `T` [[bad-assignment](https://pyrefly.org/en/docs/error-kinds/#bad-assignment)]
d2: TD[str] = {"a": 1, "b": "b"}

Needless to say that more subtle inference for T does not work either. See the sandbox link for more examples, but for instance

class Foo[T]:
    def __init__(self, b: T):
         self.td: TD[T] = {"a":1, "b":b}

# T # expected str
reveal_type(Foo("b").td["b"])

Finally, unrelated to extra_items but maybe not unrelated to the core issue is the following

class TD2[T](TypedDict):
    a: int
    b: T

d4: TD2 = {"a":1, "b":"2"}

reveal_type(d4["b"])  # Unknown  # expected str

(thank you for the lovely pyrefly tool ✨)

Sandbox Link

https://pyrefly.org/sandbox/?project=v2.pZVRa4MwFIX_ysU-tIV1ttaHIeyt7HWjy5vKaptQyzYzaroKY_99J3E20aIw9iJi7on33pN89w_IvEDKXiW2ilk6ceglKnXMXowp96w5TFkEp1qq55asG2fciohZxYOUMQvS_iurwwP38I6ozOXpjesaxC4XO1hv14ypIMF6_bgmW3d0F4XzWbiIaMOCjb5JsELDF95oWJKStgsEZ-h8ULn5BRQbircZn9Xh76JQcLtFDMWRJToWpLDyK_EynG2a38DVrX7bfhNdKYAw065ejVUYfiB3trKhC6zzwPxWQ7C9kBTO6JjwRWw2Tae6Q0w_RIXe4aRiKL0W8twVBP0Cg2E3GA5OEq9KvCmKuui0rKtCwktTtJNsU2_i4TbpksK6LZ2aumGdfJduvr8lDWfNQ1cyXFTpVGUirwExoqf6Q3PmMBpBlv0JAxjEuE2KEWavoFypjzLy_UYuj3tfFD6Xu9JvKXzSLMw-s4MZ6-3tSBqgldj2P2Qa12AaD3FprLGEiEHU_AA

(Only applicable for extension issues) IDE Information

No response

gbelouze avatar Sep 09 '26 09:09 gbelouze

I should have added that pyright handles the extra_items examples well, but also fails on the d4 example.

gbelouze avatar Sep 09 '26 10:09 gbelouze

289ab08234d66a9437ade56d88d527a8e19d4d73 fixes this bug for type variables using the new PEP 695-style syntax, and I have another fix on the way for legacy type variables.

The example on which both pyright and pyrefly infer Unknown is actually WAI:

from typing import TypedDict
class TDS[T](TypedDict):
    a: int
    b: T
d3: TDS = {"a":1, "b":"2"}
reveal_type(d3["b"])  # Unknown

When a type argument is omitted, a type checker should infer the type variable's default value, or Any if it has no default value (https://typing.python.org/en/latest/spec/generics.html#user-defined-generic-types). So TDS is treated like TDS[Any].

rchen152 avatar Sep 11 '26 22:09 rchen152