Skip to content

Commit

Permalink
Allow overlapping comparisons between bytes-like types (#14658)
Browse files Browse the repository at this point in the history
  • Loading branch information
hauntsaninja authored Feb 9, 2023
1 parent 786c7b0 commit c23e831
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
9 changes: 9 additions & 0 deletions mypy/checkexpr.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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.
Expand Down
26 changes: 26 additions & 0 deletions test-data/unit/check-flags.test
Original file line number Diff line number Diff line change
Expand Up @@ -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]

0 comments on commit c23e831

Please sign in to comment.