diff --git a/mypy/fastparse.py b/mypy/fastparse.py index e6d0881a4b9b8..d6e82ac641b8b 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -501,11 +501,12 @@ def fix_function_overloads(self, stmts: List[Statement]) -> List[Statement]: and len(stmt.body[0].body) == 1 and isinstance( stmt.body[0].body[0], (Decorator, OverloadedFuncDef)) - and infer_reachability_of_if_statement( + and infer_reachability_of_if_statement( # type: ignore[func-returns-value] stmt, self.options - ) is None # type: ignore[func-returns-value] + ) is None and stmt.body[0].is_unreachable is False ): + current_overload = [] current_overload_name = stmt.body[0].body[0].name last_if_stmt = stmt last_if_overload = stmt.body[0].body[0] @@ -518,6 +519,8 @@ def fix_function_overloads(self, stmts: List[Statement]) -> List[Statement]: ret.append(current_overload[0]) elif len(current_overload) > 1: ret.append(OverloadedFuncDef(current_overload)) + elif last_if_stmt is not None: + ret.append(last_if_stmt) return ret def in_method_scope(self) -> bool: diff --git a/test-data/unit/check-overloading.test b/test-data/unit/check-overloading.test index a63347fa2cfef..3039d77d072ad 100644 --- a/test-data/unit/check-overloading.test +++ b/test-data/unit/check-overloading.test @@ -5330,3 +5330,34 @@ def f2(g: Any) -> Any: ... reveal_type(f2(42)) # N: Revealed type is "__main__.A" reveal_type(f2("Hello")) # N: Revealed type is "__main__.A" \ # E: Argument 1 to "f2" has incompatible type "str"; expected "int" + +[case testOverloadIfOldStyle] +# flags: --always-false var_false --always-true var_true +from typing import overload, Any + +class A: ... +class B: ... + +var_true = True +var_false = False + +if var_false: + @overload + def f1(g: int) -> A: ... + @overload + def f1(g: str) -> B: ... + def f1(g: Any) -> Any: ... +elif var_true: + @overload + def f1(g: int) -> A: ... + @overload + def f1(g: str) -> B: ... + def f1(g: Any) -> Any: ... +else: + @overload + def f1(g: int) -> A: ... + @overload + def f1(g: str) -> B: ... + def f1(g: Any) -> Any: ... +reveal_type(f1(42)) # N: Revealed type is "__main__.A" +reveal_type(f1("Hello")) # N: Revealed type is "__main__.B"