Skip to content

Commit c23e831

Browse files
authored
Allow overlapping comparisons between bytes-like types (#14658)
1 parent 786c7b0 commit c23e831

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

mypy/checkexpr.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,11 @@
192192
"_collections_abc.dict_keys",
193193
"_collections_abc.dict_items",
194194
]
195+
OVERLAPPING_BYTES_ALLOWLIST: Final = {
196+
"builtins.bytes",
197+
"builtins.bytearray",
198+
"builtins.memoryview",
199+
}
195200

196201

197202
class TooManyUnions(Exception):
@@ -3164,6 +3169,10 @@ def dangerous_comparison(
31643169
return self.dangerous_comparison(left.args[0], right.args[0])
31653170
elif left_name in ("builtins.list", "builtins.tuple") and right_name == left_name:
31663171
return self.dangerous_comparison(left.args[0], right.args[0])
3172+
elif left_name in OVERLAPPING_BYTES_ALLOWLIST and right_name in (
3173+
OVERLAPPING_BYTES_ALLOWLIST
3174+
):
3175+
return False
31673176
if isinstance(left, LiteralType) and isinstance(right, LiteralType):
31683177
if isinstance(left.value, bool) and isinstance(right.value, bool):
31693178
# Comparing different booleans is not dangerous.

test-data/unit/check-flags.test

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2148,3 +2148,29 @@ def f(x: bytes) -> None: ...
21482148
f(bytearray(b"asdf"))
21492149
f(memoryview(b"asdf")) # E: Argument 1 to "f" has incompatible type "memoryview"; expected "bytes"
21502150
[builtins fixtures/primitives.pyi]
2151+
2152+
[case testDisableBytearrayMemoryviewPromotionStrictEquality]
2153+
# flags: --disable-bytearray-promotion --disable-memoryview-promotion --strict-equality
2154+
def f(x: bytes, y: bytearray, z: memoryview) -> None:
2155+
x == y
2156+
y == z
2157+
x == z
2158+
97 in x
2159+
97 in y
2160+
97 in z
2161+
x in y
2162+
x in z
2163+
[builtins fixtures/primitives.pyi]
2164+
2165+
[case testEnableBytearrayMemoryviewPromotionStrictEquality]
2166+
# flags: --strict-equality
2167+
def f(x: bytes, y: bytearray, z: memoryview) -> None:
2168+
x == y
2169+
y == z
2170+
x == z
2171+
97 in x
2172+
97 in y
2173+
97 in z
2174+
x in y
2175+
x in z
2176+
[builtins fixtures/primitives.pyi]

0 commit comments

Comments
 (0)