Repository: python/mypy
Pull request: Fix false positive: return Any from a function declared to return object
resolves #8008 

Problem statement:
False positive on returning Any from function declared to return object
mypy with `--warn-return-any` gives a warning for this function:
```python
def f() -> object:
    x: Any = 1
    return x
```
This code is correct in fact: any type is `object`, so we can safely return `Any`.
It can be fixed like that:
```python
def f() -> object:
    x: Any = 1
    return cast(object, x)
```
but `cast(object, ...)` should be a no-op for mypy IMO.

Hints from issue discussion:
I agree we can make an exception in this case. I think it is relatively low priority, but since the fix may be trivial I am setting priority to normal.

Commit message: fix warning

Patch to review:
diff --git a/mypy/checker.py b/mypy/checker.py
index 0387ffce8549..91b3ad9d19da 100644
--- a/mypy/checker.py
+++ b/mypy/checker.py
@@ -3036,7 +3036,9 @@ def check_return_stmt(self, s: ReturnStmt) -> None:
                         and not self.current_node_deferred
                         and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)
                         and not (defn.name in BINARY_MAGIC_METHODS and
-                                 is_literal_not_implemented(s.expr))):
+                                 is_literal_not_implemented(s.expr))
+                        and not (isinstance(return_type, Instance) and
+                                return_type.type.fullname == 'builtins.object')):
                         self.msg.incorrectly_returning_any(return_type, s)
                     return
 
diff --git a/test-data/unit/check-basic.test b/test-data/unit/check-basic.test
index e6f7f98de200..313f0446871c 100644
--- a/test-data/unit/check-basic.test
+++ b/test-data/unit/check-basic.test
@@ -466,3 +466,11 @@ a = (a.A(), A())
 a.x  # E: "Tuple[a.A, b.A]" has no attribute "x"
 
 [builtins fixtures/dict.pyi]
+
+[case testReturnAnyFromFunctionDeclaredToReturnObject]
+# flags: --warn-return-any
+from typing import Any
+
+def f() -> object:
+    x: Any = 1
+    return x


Code review comments:
diff_hunk: @@ -3036,7 +3036,9 @@ def check_return_stmt(self, s: ReturnStmt) -> None:
                         and not self.current_node_deferred
                         and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)
                         and not (defn.name in BINARY_MAGIC_METHODS and
-                                 is_literal_not_implemented(s.expr))):
+                                 is_literal_not_implemented(s.expr))
+                        and not (isinstance(return_type, Instance) and
+                                return_type.type.fullname == 'builtins.object')):
path: mypy/checker.py
text: @user1:
```suggestion
                                 return_type.type.fullname == 'builtins.object')):
```