summaryrefslogtreecommitdiff
path: root/tests/basics/class_reverse_op.py
diff options
context:
space:
mode:
authorDamien George <damien@micropython.org>2023-05-12 23:17:20 +1000
committerDamien George <damien@micropython.org>2023-05-19 13:42:35 +1000
commit4b57330465b98df30ef8a10e19a0e197b5797550 (patch)
treeb3a674e8cb6673ab451d6ef6d97ec29aed910a6b /tests/basics/class_reverse_op.py
parentca9068e0efc5e53ff7042ef68ad4a4ec9ff91915 (diff)
py/objstr: Return unsupported binop instead of raising TypeError.
So that user types can implement reverse operators and have them work with str on the left-hand-side, eg `"a" + UserType()`. Signed-off-by: Damien George <damien@micropython.org>
Diffstat (limited to 'tests/basics/class_reverse_op.py')
-rw-r--r--tests/basics/class_reverse_op.py32
1 files changed, 31 insertions, 1 deletions
diff --git a/tests/basics/class_reverse_op.py b/tests/basics/class_reverse_op.py
index b0dae5f8a..11aba6aad 100644
--- a/tests/basics/class_reverse_op.py
+++ b/tests/basics/class_reverse_op.py
@@ -1,5 +1,7 @@
-class A:
+# Test reverse operators.
+# Test user type with integers.
+class A:
def __init__(self, v):
self.v = v
@@ -14,5 +16,33 @@ class A:
def __repr__(self):
return "A({})".format(self.v)
+
print(A(3) + 1)
print(2 + A(5))
+
+
+# Test user type with strings.
+class B:
+ def __init__(self, v):
+ self.v = v
+
+ def __repr__(self):
+ return "B({})".format(self.v)
+
+ def __ror__(self, o):
+ return B(o + "|" + self.v)
+
+ def __radd__(self, o):
+ return B(o + "+" + self.v)
+
+ def __rmul__(self, o):
+ return B(o + "*" + self.v)
+
+ def __rtruediv__(self, o):
+ return B(o + "/" + self.v)
+
+
+print("a" | B("b"))
+print("a" + B("b"))
+print("a" * B("b"))
+print("a" / B("b"))