Environment
- Pyright Version: 1.1.411
- Python Version: 3.13.14
Bug Description
When iterating over a tuple of string literal keys (e.g. for key in ("anyOf", "oneOf"):) and guarding a key lookup on a total=False (or NotRequired) TypedDict using if key in typed_dict:, Pyright fails to perform type narrowing on typed_dict[key].
Instead, Pyright raises a false positive reportTypedDictNotRequiredAccess warning:
Could not access item in TypedDict
"anyOf" is not a required key in "JsonSchema", so access may result in runtime exception
"oneOf" is not a required key in "JsonSchema", so access may result in runtime exception
Even though if key in typed_dict: guarantees at runtime that key exists before indexing typed_dict[key], Pyright fails to apply narrowing when key is a union of literal string types.
Minimal Code Example (Repro)
pyright playground
from typing import TypedDict
class JsonSchema(TypedDict, total=False):
anyOf: list['JsonSchema']
oneOf: list['JsonSchema']
def process_schema(schema: JsonSchema) -> None:
for keyword in ("anyOf", "oneOf"):
if keyword in schema:
reveal_type(keyword) # Type of "keyword" is "Literal['anyOf', 'oneOf']"
sub_schemas = schema[keyword] # reportTypedDictNotRequiredAccess
print(len(sub_schemas))
Expected Behavior
Pyright should recognize if keyword in schema: as a valid narrowing guard for TypedDict keys when keyword is a Literal["anyOf", "oneOf"] (or a str union of valid TypedDict keys), permitting safe indexing schema[keyword].
Environment
Bug Description
When iterating over a tuple of string literal keys (e.g.
for key in ("anyOf", "oneOf"):) and guarding a key lookup on atotal=False(orNotRequired)TypedDictusingif key in typed_dict:, Pyright fails to perform type narrowing ontyped_dict[key].Instead, Pyright raises a false positive
reportTypedDictNotRequiredAccesswarning:Even though
if key in typed_dict:guarantees at runtime thatkeyexists before indexingtyped_dict[key], Pyright fails to apply narrowing whenkeyis a union of literal string types.Minimal Code Example (Repro)
pyright playground
Expected Behavior
Pyright should recognize
if keyword in schema:as a valid narrowing guard forTypedDictkeys whenkeywordis aLiteral["anyOf", "oneOf"](or astrunion of validTypedDictkeys), permitting safe indexingschema[keyword].