Skip to content

Commit 376618c

Browse files
committed
tests/class_inplace_op: Test for inplace op fallback to normal one.
1 parent 60749e5 commit 376618c

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

tests/basics/class_inplace_op.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Case 1: Immutable object (e.g. number-like)
2+
# __iadd__ should not be defined, will be emulated using __add__
3+
4+
class A:
5+
6+
def __init__(self, v):
7+
self.v = v
8+
9+
def __add__(self, o):
10+
return A(self.v + o.v)
11+
12+
def __repr__(self):
13+
return "A(%s)" % self.v
14+
15+
a = A(5)
16+
b = a
17+
a += A(3)
18+
print(a)
19+
# Should be original a's value, i.e. A(5)
20+
print(b)
21+
22+
# Case 2: Mutable object (e.g. list-like)
23+
# __iadd__ should be defined
24+
25+
class L:
26+
27+
def __init__(self, v):
28+
self.v = v
29+
30+
def __add__(self, o):
31+
# Should not be caled in this test
32+
print("L.__add__")
33+
return L(self.v + o.v)
34+
35+
def __iadd__(self, o):
36+
self.v += o.v
37+
return self
38+
39+
def __repr__(self):
40+
return "L(%s)" % self.v
41+
42+
c = L([1, 2])
43+
d = c
44+
c += L([3, 4])
45+
print(c)
46+
# Should be updated c's value, i.e. L([1, 2, 3, 4])
47+
print(d)

0 commit comments

Comments
 (0)