Skip to content

Commit e7e3dfd

Browse files
authored
Allow reflected fallback for in-place set operators (#9182)
Assisted-by: Codex:gpt-6
1 parent e411f91 commit e7e3dfd

2 files changed

Lines changed: 28 additions & 4 deletions

File tree

‎crates/vm/src/builtins/set.rs‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,7 +1151,9 @@ impl AsNumber for PySet {
11511151
}
11521152
}),
11531153
inplace_subtract: Some(|a, b, vm| {
1154-
if let Some(a) = a.downcast_ref::<PySet>() {
1154+
if let Some(a) = a.downcast_ref::<PySet>()
1155+
&& PyRef::<PyAnySet>::check(b, vm)
1156+
{
11551157
PySet::__isub__(
11561158
a.to_owned(),
11571159
PyRef::<PyAnySet>::try_from_object(vm, b.to_owned())?,
@@ -1163,7 +1165,9 @@ impl AsNumber for PySet {
11631165
}
11641166
}),
11651167
inplace_and: Some(|a, b, vm| {
1166-
if let Some(a) = a.downcast_ref::<PySet>() {
1168+
if let Some(a) = a.downcast_ref::<PySet>()
1169+
&& PyRef::<PyAnySet>::check(b, vm)
1170+
{
11671171
PySet::__iand__(
11681172
a.to_owned(),
11691173
PyRef::<PyAnySet>::try_from_object(vm, b.to_owned())?,
@@ -1175,7 +1179,9 @@ impl AsNumber for PySet {
11751179
}
11761180
}),
11771181
inplace_xor: Some(|a, b, vm| {
1178-
if let Some(a) = a.downcast_ref::<PySet>() {
1182+
if let Some(a) = a.downcast_ref::<PySet>()
1183+
&& PyRef::<PyAnySet>::check(b, vm)
1184+
{
11791185
PySet::__ixor__(
11801186
a.to_owned(),
11811187
PyRef::<PyAnySet>::try_from_object(vm, b.to_owned())?,
@@ -1187,7 +1193,9 @@ impl AsNumber for PySet {
11871193
}
11881194
}),
11891195
inplace_or: Some(|a, b, vm| {
1190-
if let Some(a) = a.downcast_ref::<PySet>() {
1196+
if let Some(a) = a.downcast_ref::<PySet>()
1197+
&& PyRef::<PyAnySet>::check(b, vm)
1198+
{
11911199
PySet::__ior__(
11921200
a.to_owned(),
11931201
PyRef::<PyAnySet>::try_from_object(vm, b.to_owned())?,

‎extra_tests/snippets/builtin_set.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import operator
2+
13
from testutils import assert_raises
24

35
assert set([1, 2]) == set([1, 2])
@@ -706,3 +708,17 @@ def __del__(self):
706708
intersection_target.intersection_update({1})
707709
assert not intersection_target
708710
assert intersection_events == [True, True]
711+
712+
713+
# Unsupported right operands must reach their reflected set operation.
714+
keys = {2: None, 3: None}.keys()
715+
for method, operation, expected in (
716+
(set.__ior__, operator.ior, {1, 2, 3}),
717+
(set.__iand__, operator.iand, {2}),
718+
(set.__isub__, operator.isub, {1}),
719+
(set.__ixor__, operator.ixor, {1, 3}),
720+
):
721+
source = {1, 2}
722+
assert method(source, keys) is NotImplemented
723+
assert operation(source, keys) == expected
724+
assert source == {1, 2}

0 commit comments

Comments
 (0)