Skip to content

Commit 6050204

Browse files
authored
Allow bytearray/bytes comparisons with --disable-bytearray-promotion (#18255)
Previously comparing a bytearray against a bytes literal was reported as a non-overlapping comparison when using `--strict-equality`. This was a false positive. This is in preparation for disabling bytearray to bytes promotion by default in mypy 2.0.
1 parent 82de0d8 commit 6050204

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

mypy/checkexpr.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3790,6 +3790,18 @@ def dangerous_comparison(
37903790
if isinstance(left.value, bool) and isinstance(right.value, bool):
37913791
# Comparing different booleans is not dangerous.
37923792
return False
3793+
if isinstance(left, LiteralType) and isinstance(right, Instance):
3794+
# bytes/bytearray comparisons are supported
3795+
if left.fallback.type.fullname == "builtins.bytes" and right.type.has_base(
3796+
"builtins.bytearray"
3797+
):
3798+
return False
3799+
if isinstance(right, LiteralType) and isinstance(left, Instance):
3800+
# bytes/bytearray comparisons are supported
3801+
if right.fallback.type.fullname == "builtins.bytes" and left.type.has_base(
3802+
"builtins.bytearray"
3803+
):
3804+
return False
37933805
return not is_overlapping_types(left, right, ignore_promotions=False)
37943806

37953807
def check_method_call_by_name(

test-data/unit/check-flags.test

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2345,10 +2345,19 @@ x: int = "" # E: Incompatible types in assignment (expression has type "str", v
23452345
x: int = "" # E: Incompatible types in assignment (expression has type "str", variable has type "int")
23462346

23472347
[case testDisableBytearrayPromotion]
2348-
# flags: --disable-bytearray-promotion
2348+
# flags: --disable-bytearray-promotion --strict-equality
23492349
def f(x: bytes) -> None: ...
23502350
f(bytearray(b"asdf")) # E: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"
23512351
f(memoryview(b"asdf"))
2352+
ba = bytearray(b"")
2353+
if ba == b"":
2354+
f(ba) # E: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"
2355+
if b"" == ba:
2356+
f(ba) # E: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"
2357+
if ba == bytes():
2358+
f(ba) # E: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"
2359+
if bytes() == ba:
2360+
f(ba) # E: Argument 1 to "f" has incompatible type "bytearray"; expected "bytes"
23522361
[builtins fixtures/primitives.pyi]
23532362

23542363
[case testDisableMemoryviewPromotion]

0 commit comments

Comments
 (0)