From 301072dd35ea54145b25ba0c99c79af04df087bc Mon Sep 17 00:00:00 2001 From: Marc Mueller <30130371+cdce8p@users.noreply.github.com> Date: Fri, 25 Jun 2021 23:52:17 +0200 Subject: [PATCH] Bugfix --- mypy/fastparse.py | 7 ++++-- test-data/unit/check-overloading.test | 31 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 2 deletions(-) diff --git a/mypy/fastparse.py b/mypy/fastparse.py index 56723ee295f04..efdbb29cd787c 100644 --- a/mypy/fastparse.py +++ b/mypy/fastparse.py @@ -509,11 +509,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] @@ -526,6 +527,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 d6831c03a69a0..8cf7833056ced 100644 --- a/test-data/unit/check-overloading.test +++ b/test-data/unit/check-overloading.test @@ -5496,3 +5496,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"