diff --git a/mypy/checkexpr.py b/mypy/checkexpr.py index 4cfbd0811025..754ba6f093f5 100644 --- a/mypy/checkexpr.py +++ b/mypy/checkexpr.py @@ -192,6 +192,11 @@ "_collections_abc.dict_keys", "_collections_abc.dict_items", ] +OVERLAPPING_BYTES_ALLOWLIST: Final = { + "builtins.bytes", + "builtins.bytearray", + "builtins.memoryview", +} class TooManyUnions(Exception): @@ -3164,6 +3169,10 @@ def dangerous_comparison( return self.dangerous_comparison(left.args[0], right.args[0]) elif left_name in ("builtins.list", "builtins.tuple") and right_name == left_name: return self.dangerous_comparison(left.args[0], right.args[0]) + elif left_name in OVERLAPPING_BYTES_ALLOWLIST and right_name in ( + OVERLAPPING_BYTES_ALLOWLIST + ): + return False if isinstance(left, LiteralType) and isinstance(right, LiteralType): if isinstance(left.value, bool) and isinstance(right.value, bool): # Comparing different booleans is not dangerous. diff --git a/test-data/unit/check-flags.test b/test-data/unit/check-flags.test index ebb3744e9f08..0ac39ebf9c10 100644 --- a/test-data/unit/check-flags.test +++ b/test-data/unit/check-flags.test @@ -2148,3 +2148,29 @@ def f(x: bytes) -> None: ... f(bytearray(b"asdf")) f(memoryview(b"asdf")) # E: Argument 1 to "f" has incompatible type "memoryview"; expected "bytes" [builtins fixtures/primitives.pyi] + +[case testDisableBytearrayMemoryviewPromotionStrictEquality] +# flags: --disable-bytearray-promotion --disable-memoryview-promotion --strict-equality +def f(x: bytes, y: bytearray, z: memoryview) -> None: + x == y + y == z + x == z + 97 in x + 97 in y + 97 in z + x in y + x in z +[builtins fixtures/primitives.pyi] + +[case testEnableBytearrayMemoryviewPromotionStrictEquality] +# flags: --strict-equality +def f(x: bytes, y: bytearray, z: memoryview) -> None: + x == y + y == z + x == z + 97 in x + 97 in y + 97 in z + x in y + x in z +[builtins fixtures/primitives.pyi]