diff --git a/mypy/checker.py b/mypy/checker.py index c3d1ad60c18f..de0184863525 100644 --- a/mypy/checker.py +++ b/mypy/checker.py @@ -1758,8 +1758,6 @@ def visit_try_stmt(self, s: TryStmt) -> Type: self.binder.try_frames.add(len(self.binder.frames) - 2) self.accept(s.body) self.binder.try_frames.remove(len(self.binder.frames) - 2) - if s.else_body: - self.accept(s.else_body) self.breaking_out = False changed, frame_on_completion = self.binder.pop_frame() completed_frames.append(frame_on_completion) @@ -1794,6 +1792,14 @@ def visit_try_stmt(self, s: TryStmt) -> Type: changed, frame_on_completion = self.binder.pop_frame() completed_frames.append(frame_on_completion) + # Do the else block similar to the way we do except blocks. + if s.else_body: + self.binder.push_frame() + self.accept(s.else_body) + self.breaking_out = False + changed, frame_on_completion = self.binder.pop_frame() + completed_frames.append(frame_on_completion) + self.binder.update_from_options(completed_frames) if s.finally_body: diff --git a/mypy/test/data/check-statements.test b/mypy/test/data/check-statements.test index 3b98693742b6..119042c363d2 100644 --- a/mypy/test/data/check-statements.test +++ b/mypy/test/data/check-statements.test @@ -516,6 +516,24 @@ else: object(None) # E: Too many arguments for "object" [builtins fixtures/exception.py] +[case testRedefinedFunctionInTryWithElse] +def f() -> None: pass +try: + pass +except BaseException: + f2 = f +else: + def f2() -> str: pass +try: + pass +except BaseException: + f3 = f +else: + def f3() -> None: pass +[builtins fixtures/exception.py] +[out] +main:7: error: Incompatible redefinition (original type Callable[[], None], redefinition with type Callable[[], str]) + [case testExceptWithoutType] import typing try: