Skip to content

Commit 0b5efee

Browse files
author
Guido van Rossum
committed
Correctly type check redefinitions in try's else clause.
Fixes #1289. After a diff in the issue by @Brodie.
1 parent 7b156c2 commit 0b5efee

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

mypy/checker.py

+8-3
Original file line numberDiff line numberDiff line change
@@ -1758,9 +1758,6 @@ def visit_try_stmt(self, s: TryStmt) -> Type:
17581758
self.binder.try_frames.add(len(self.binder.frames) - 2)
17591759
self.accept(s.body)
17601760
self.binder.try_frames.remove(len(self.binder.frames) - 2)
1761-
if s.else_body:
1762-
self.accept(s.else_body)
1763-
self.breaking_out = False
17641761
changed, frame_on_completion = self.binder.pop_frame()
17651762
completed_frames.append(frame_on_completion)
17661763

@@ -1794,6 +1791,14 @@ def visit_try_stmt(self, s: TryStmt) -> Type:
17941791
changed, frame_on_completion = self.binder.pop_frame()
17951792
completed_frames.append(frame_on_completion)
17961793

1794+
# Do the else block similar to the way we do except blocks.
1795+
if s.else_body:
1796+
self.binder.push_frame()
1797+
self.accept(s.else_body)
1798+
self.breaking_out = False
1799+
changed, frame_on_completion = self.binder.pop_frame()
1800+
completed_frames.append(frame_on_completion)
1801+
17971802
self.binder.update_from_options(completed_frames)
17981803

17991804
if s.finally_body:

mypy/test/data/check-statements.test

+18
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,24 @@ else:
516516
object(None) # E: Too many arguments for "object"
517517
[builtins fixtures/exception.py]
518518

519+
[case testRedefinedFunctionInTryWithElse]
520+
def f() -> None: pass
521+
try:
522+
pass
523+
except BaseException:
524+
f2 = f
525+
else:
526+
def f2() -> str: pass
527+
try:
528+
pass
529+
except BaseException:
530+
f3 = f
531+
else:
532+
def f3() -> None: pass
533+
[builtins fixtures/exception.py]
534+
[out]
535+
main:7: error: Incompatible redefinition (original type Callable[[], None], redefinition with type Callable[[], str])
536+
519537
[case testExceptWithoutType]
520538
import typing
521539
try:

0 commit comments

Comments
 (0)