Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions packages/pyright-internal/src/analyzer/typedDicts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -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.
15 changes: 15 additions & 0 deletions packages/pyright-internal/src/tests/typeEvaluator5.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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']);

Expand Down