diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index e74960241d1e..c4da53124fdc 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -2028,6 +2028,19 @@ def dangerous_comparison(self, left: Type, right: Type, """ if not self.chk.options.strict_equality: return False + if self.chk.binder.is_unreachable_warning_suppressed(): + # We are inside a function that contains type variables with value restrictions in + # its signature. In this case we just suppress all strict-equality checks to avoid + # false positives for code like: + # + # T = TypeVar('T', str, int) + # def f(x: T) -> T: + # if x == 0: + # ... + # return x + # + # TODO: find a way of disabling the check only for types resulted from the expansion. + return False if isinstance(left, NoneType) or isinstance(right, NoneType): return False if isinstance(left, UnionType) and isinstance(right, UnionType): diff --git a/test-data/unit/check-expressions.test b/test-data/unit/check-expressions.test index 58d70a6cda34..69614287c1fc 100644 --- a/test-data/unit/check-expressions.test +++ b/test-data/unit/check-expressions.test @@ -2259,6 +2259,18 @@ class Custom: Custom() == int() [builtins fixtures/bool.pyi] +[case testStrictEqualityDisabledWithTypeVarRestrictions] +# flags: --strict-equality +from typing import TypeVar + +T = TypeVar('T', str, int) + +def f(x: T) -> T: + if x == int(): # OK + ... + return x +[builtins fixtures/bool.pyi] + [case testUnimportedHintAny] def f(x: Any) -> None: # E: Name 'Any' is not defined \ # N: Did you forget to import it from "typing"? (Suggestion: "from typing import Any")