py/objset: Check that RHS of a binary op is a set/frozenset.
CPython docs explicitly state that the RHS of a set/frozenset binary op
must be a set to prevent user errors. It also preserves commutativity of
the ops, eg: "abc" & set() is a TypeError, and so should be set() & "abc".
This change actually decreases unix (x64) code by 160 bytes; it increases
stm32 by 4 bytes and esp8266 by 28 bytes (but previous patch already
introduced a much large saving).
diff --git a/py/objset.c b/py/objset.c
index 6dede88..80ed263 100644
--- a/py/objset.c
+++ b/py/objset.c
@@ -463,6 +463,10 @@
#else
bool update = true;
#endif
+ if (op != MP_BINARY_OP_IN && !is_set_or_frozenset(rhs)) {
+ // For all ops except containment the RHS must be a set/frozenset
+ return MP_OBJ_NULL;
+ }
switch (op) {
case MP_BINARY_OP_OR:
return set_union(lhs, rhs);
diff --git a/tests/basics/set_binop.py b/tests/basics/set_binop.py
index 7848920..bc76533 100644
--- a/tests/basics/set_binop.py
+++ b/tests/basics/set_binop.py
@@ -47,6 +47,18 @@
s1 -= set('ad')
print(s1 is s2, len(s1))
+# RHS must be a set
+try:
+ print(set('12') >= '1')
+except TypeError:
+ print('TypeError')
+
+# RHS must be a set
+try:
+ print(set('12') <= '123')
+except TypeError:
+ print('TypeError')
+
# unsupported operator
try:
set('abc') * 2
diff --git a/tests/misc/non_compliant.py b/tests/misc/non_compliant.py
index b4c90e9..152633c 100644
--- a/tests/misc/non_compliant.py
+++ b/tests/misc/non_compliant.py
@@ -39,18 +39,6 @@
except NotImplementedError:
print('NotImplementedError')
-# should raise type error
-try:
- print(set('12') >= '1')
-except TypeError:
- print('TypeError')
-
-# should raise type error
-try:
- print(set('12') <= '123')
-except TypeError:
- print('TypeError')
-
# uPy raises TypeError, shold be ValueError
try:
'%c' % b'\x01\x02'
diff --git a/tests/misc/non_compliant.py.exp b/tests/misc/non_compliant.py.exp
index ba5590a..9c157fd 100644
--- a/tests/misc/non_compliant.py.exp
+++ b/tests/misc/non_compliant.py.exp
@@ -3,8 +3,6 @@
TypeError
NotImplementedError
NotImplementedError
-True
-True
TypeError, ValueError
NotImplementedError
NotImplementedError