diff --git a/packages/pyright-internal/src/analyzer/typedDicts.ts b/packages/pyright-internal/src/analyzer/typedDicts.ts index 42a4d676e6b1..e09910b43f29 100644 --- a/packages/pyright-internal/src/analyzer/typedDicts.ts +++ b/packages/pyright-internal/src/analyzer/typedDicts.ts @@ -1739,9 +1739,15 @@ export function getTypeOfIndexedTypedDict( return subtype; } - if (isClassInstance(subtype) && ClassType.isBuiltIn(subtype, 'str')) { + // The existing non-literal str mutation path does not validate possible + // keys, so do not extend it to LiteralString mutations. + if ( + isClassInstance(subtype) && + (ClassType.isBuiltIn(subtype, 'str') || + (usage.method === 'get' && ClassType.isBuiltIn(subtype, 'LiteralString'))) + ) { if (subtype.priv.literalValue === undefined) { - // If it's a plain str with no literal value, we can't + // If it's a string with no literal value, we can't // make any determination about the resulting type. return UnknownType.create(); } diff --git a/packages/pyright-internal/src/tests/samples/typedDictLiteralString1.py b/packages/pyright-internal/src/tests/samples/typedDictLiteralString1.py new file mode 100644 index 000000000000..bf9d08c28dbc --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/typedDictLiteralString1.py @@ -0,0 +1,70 @@ +# This sample tests reads and unsafe mutations using a LiteralString key +# whose value is not known statically. + +from typing import Literal, LiteralString, TypedDict, reveal_type +from typing_extensions import ReadOnly # pyright: ignore[reportMissingModuleSource] + + +class TD1(TypedDict, extra_items=str): + known: int + + +class TD2(TypedDict): + known: int + + +class TD3(TypedDict, closed=True): + known: int + + +class TDReadOnly(TypedDict): + protected: ReadOnly[int] + + +class TDMixed(TypedDict, extra_items=int | str): + value: int | str + + +def func1( + td1: TD1, + td2: TD2, + td3: TD3, + readonly: TDReadOnly, + mixed: TDMixed, + plain_dict: dict[str, int], + k: LiteralString, + s: str, + lit: Literal["known"], +) -> None: + reveal_type(td1[k], expected_text="Unknown") + reveal_type(td1[s], expected_text="Unknown") + reveal_type(td2[k], expected_text="Unknown") + reveal_type(td3[k], expected_text="Unknown") + reveal_type(td1[lit], expected_text="int") + reveal_type(readonly["protected"], expected_text="int") + + td1[lit] = 1 + known: LiteralString = "known" + td1[known] = 1 + plain_dict[k] = 1 + del plain_dict[k] + + td1[k] = "a" # This should generate an error. + td2[k] = 1 # This should generate an error. + td3[k] = 1 # This should generate an error. + + del td1[k] # This should generate an error. + del td2[k] # This should generate an error. + del td3[k] # This should generate an error. + + readonly[k] = 1 # This should generate an error. + del readonly[k] # This should generate an error. + + if isinstance(mixed["value"], str): + mixed[k] = 1 # This should generate an error. + + td2[k] += 1 # This should generate an error. + + td3["other"] # This should generate an error. + td1["known"] = "a" # This should generate an error. + del td1["known"] # This should generate an error. diff --git a/packages/pyright-internal/src/tests/typeEvaluator5.test.ts b/packages/pyright-internal/src/tests/typeEvaluator5.test.ts index dba285a01535..cf92212b8b45 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator5.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator5.test.ts @@ -452,6 +452,21 @@ test('TypedDictClosed12', () => { TestUtils.validateResults(analysisResults, 0); }); +test('TypedDictLiteralString1', () => { + const analysisResults = TestUtils.typeAnalyzeSampleFiles(['typedDictLiteralString1.py']); + const expectedLines = TestUtils.readSampleFile('typedDictLiteralString1.py') + .split(/\r?\n/) + .flatMap((line, index) => (line.includes('# This should generate an error.') ? [index] : [])); + TestUtils.validateResults(analysisResults, expectedLines.length); + assert.deepStrictEqual( + analysisResults[0].errors.map((diagnostic) => diagnostic.range.start.line), + expectedLines + ); + analysisResults[0].errors.forEach((diagnostic) => + assert.strictEqual(diagnostic.getRule(), DiagnosticRule.reportGeneralTypeIssues) + ); +}); + test('DataclassTransform1', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['dataclassTransform1.py']);