From d5c1ff5f8e68eed089afaef734a6e9e12d5a0063 Mon Sep 17 00:00:00 2001 From: Hiroshi Ogawa Date: Sun, 3 Oct 2021 21:33:39 +0900 Subject: [PATCH] fix(11060): check `left_expr` in `check_generator_or_comprehension` This is to detect invalid usage of variables in `AssignmentExpr` hidden inside `left_expr`. Otherwise, such error is shadowed by the inference based on "synthetic generic callable". --- mypy/checkexpr.py | 3 +++ test-data/unit/check-python38.test | 25 +++++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 280e9a35d5372..8a7a387ff1491 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -3761,6 +3761,9 @@ def check_generator_or_comprehension(self, gen: GeneratorExpr, with self.chk.binder.frame_context(can_skip=True, fall_through=0): self.check_for_comp(gen) + # Check `left_expr` to analyze variables introduced by `AssignmentExpr` if any + gen.left_expr.accept(self) + # Infer the type of the list comprehension by using a synthetic generic # callable type. tv = TypeVarType('T', 'T', -1, [], self.object_type()) diff --git a/test-data/unit/check-python38.test b/test-data/unit/check-python38.test index f033f7e65e018..54f7d206f833c 100644 --- a/test-data/unit/check-python38.test +++ b/test-data/unit/check-python38.test @@ -546,3 +546,28 @@ def foo() -> None: x = 0 [x := x + y for y in [1, 2, 3]] [builtins fixtures/dict.pyi] + +[case testWalrusUndefinedRecursiveReference1] +(x := x) # E: Cannot determine type of "x" + +[case testWalrusUndefinedRecursiveReference2] +z = [x := x for y in [1, 2, 3]] # E: Cannot determine type of "x" + +[case testWalrusUndefinedRecursiveReference3] +from typing import Any + +def f(x: Any) -> None: + pass + +f(x := x) # E: Cannot determine type of "x" + +[case testWalrusUndefinedRecursiveReference4] +from typing import TypeVar + +T = TypeVar("T") + +def f(x: T) -> None: + pass + +# TODO: should be the same error as others? +f(x := x)