From 13f35ad0915e70c2c299e2eb308968c86117132d Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Thu, 4 May 2023 16:29:39 +0100 Subject: [PATCH] Fix crash related to propagating type narrowing to nested functions (#15181) See https://github.com/python/mypy/pull/15133#issuecomment-1533794642 for context. --- mypy/checker.py | 1 + test-data/unit/check-optional.test | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/mypy/checker.py b/mypy/checker.py index fd9ce02626bd..f81cb7a1fd32 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -1222,6 +1222,7 @@ def check_func_def( if new_frame is None: new_frame = self.binder.push_frame() new_frame.types[key] = narrowed_type + self.binder.declarations[key] = old_binder.declarations[key] with self.scope.push_function(defn): # We suppress reachability warnings when we use TypeVars with value # restrictions: we only want to report a warning if a certain statement is diff --git a/test-data/unit/check-optional.test b/test-data/unit/check-optional.test index 8ccce5115aba..ae247b0047f1 100644 --- a/test-data/unit/check-optional.test +++ b/test-data/unit/check-optional.test @@ -1329,3 +1329,17 @@ def narrow_with_multi_assign_3(x: Optional[str]) -> None: y, x = None, None [builtins fixtures/isinstance.pyi] + +[case testNestedFunctionSpecialCase] +class C: + def __enter__(self, *args): ... + def __exit__(self, *args) -> bool: ... + +def f(x: object) -> None: + if x is not None: + pass + + def nested() -> None: + with C(): + pass +[builtins fixtures/tuple.pyi]