From 5ee5dcb6d1e8fcb5f87bad9a930bb9f5e21f6073 Mon Sep 17 00:00:00 2001 From: hauntsaninja Date: Wed, 7 Jun 2023 21:32:58 -0700 Subject: [PATCH] Fix crash when indexing TypedDict with empty key Fixes #15389 --- mypy/messages.py | 3 ++- test-data/unit/check-typeddict.test | 12 ++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/mypy/messages.py b/mypy/messages.py index a732d612123c..cb95fb1c0bde 100644 --- a/mypy/messages.py +++ b/mypy/messages.py @@ -2989,8 +2989,9 @@ def _real_quick_ratio(a: str, b: str) -> float: def best_matches(current: str, options: Collection[str], n: int) -> list[str]: + if not current: + return [] # narrow down options cheaply - assert current options = [o for o in options if _real_quick_ratio(current, o) > 0.75] if len(options) >= 50: options = [o for o in options if abs(len(o) - len(current)) <= 1] diff --git a/test-data/unit/check-typeddict.test b/test-data/unit/check-typeddict.test index 970dc05b488d..fc487d2d553d 100644 --- a/test-data/unit/check-typeddict.test +++ b/test-data/unit/check-typeddict.test @@ -2873,3 +2873,15 @@ foo({"foo": {"e": "foo"}}) # E: Type of TypedDict is ambiguous, none of ("A", " # E: Argument 1 to "foo" has incompatible type "Dict[str, Dict[str, str]]"; expected "Union[A, B]" [builtins fixtures/dict.pyi] [typing fixtures/typing-typeddict.pyi] + +[case testTypedDictMissingEmptyKey] +from typing_extensions import TypedDict + +class A(TypedDict): + my_attr_1: str + my_attr_2: int + +d: A +d[''] # E: TypedDict "A" has no key "" +[builtins fixtures/dict.pyi] +[typing fixtures/typing-typeddict.pyi]