-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathrun-dunders.test
More file actions
1011 lines (813 loc) · 22.1 KB
/
run-dunders.test
File metadata and controls
1011 lines (813 loc) · 22.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Test cases for (some) dunder methods (compile and run)
[case testDundersMisc]
# Legacy test case for dunders (don't add more here)
from typing import Any
class Item:
def __init__(self, value: str) -> None:
self.value = value
def __hash__(self) -> int:
return hash(self.value)
def __eq__(self, rhs: object) -> bool:
return isinstance(rhs, Item) and self.value == rhs.value
def __lt__(self, x: 'Item') -> bool:
return self.value < x.value
class Subclass1(Item):
def __bool__(self) -> bool:
return bool(self.value)
class NonBoxedThing:
def __getitem__(self, index: Item) -> Item:
return Item("2 * " + index.value + " + 1")
class BoxedThing:
def __getitem__(self, index: int) -> int:
return 2 * index + 1
class Subclass2(BoxedThing):
pass
def index_into(x : Any, y : Any) -> Any:
return x[y]
def internal_index_into() -> None:
x = BoxedThing()
print (x[3])
y = NonBoxedThing()
z = Item("3")
print(y[z].value)
def is_truthy(x: Item) -> bool:
return True if x else False
[file driver.py]
from native import *
x = BoxedThing()
y = 3
print(x[y], index_into(x, y))
x = Subclass2()
y = 3
print(x[y], index_into(x, y))
z = NonBoxedThing()
w = Item("3")
print(z[w].value, index_into(z, w).value)
i1 = Item('lolol')
i2 = Item('lol' + 'ol')
i3 = Item('xyzzy')
assert hash(i1) == hash(i2)
assert i1 == i2
assert not i1 != i2
assert not i1 == i3
assert i1 != i3
assert i2 < i3
assert not i1 < i2
assert i1 == Subclass1('lolol')
assert is_truthy(Item(''))
assert is_truthy(Item('a'))
assert not is_truthy(Subclass1(''))
assert is_truthy(Subclass1('a'))
internal_index_into()
[out]
7 7
7 7
2 * 3 + 1 2 * 3 + 1
7
2 * 3 + 1
[case testDundersContainer]
# Sequence/mapping dunder methods
from typing import Any
class Seq:
def __init__(self) -> None:
self.key = 0
self.value = 0
def __len__(self) -> int:
return 5
def __setitem__(self, key: int, value: int) -> None:
self.key = key
self.value = value
def __contains__(self, x: int) -> bool:
return x == 3
def __delitem__(self, key: int) -> None:
self.key = key
class Plain: pass
def any_seq() -> Any:
"""Return Any-typed Seq."""
return Seq()
def any_plain() -> Any:
"""Return Any-typed Seq."""
return Plain()
def test_len() -> None:
assert len(any_seq()) == 5
assert len(Seq()) == 5
def test_len_error() -> None:
try:
len(any_plain())
except TypeError:
pass
else:
assert False
def test_set_item() -> None:
s = any_seq()
s[44] = 66
assert s.key == 44 and s.value == 66
ss = Seq()
ss[33] = 55
assert ss.key == 33 and ss.value == 55
def test_contains() -> None:
assert 3 in any_seq()
assert 4 not in any_seq()
assert 2 not in any_seq()
assert 3 in Seq()
assert 4 not in Seq()
assert 2 not in Seq()
def test_delitem() -> None:
s = any_seq()
del s[55]
assert s.key == 55
class SeqAny:
def __contains__(self, x: Any) -> Any:
return x == 3
def __setitem__(self, x: Any, y: Any) -> Any:
self.x = x
return 'x'
def test_contains_any() -> None:
assert (3 in SeqAny()) is True
assert (2 in SeqAny()) is False
assert (3 not in SeqAny()) is False
assert (2 not in SeqAny()) is True
s = SeqAny() # type: Any
assert (3 in s) is True
assert (2 in s) is False
assert (3 not in s) is False
assert (2 not in s) is True
def test_set_item_any() -> None:
s = SeqAny()
s[4] = 6
assert s.x == 4
ss = SeqAny() # type: Any
ss[5] = 7
assert ss.x == 5
class SeqError:
def __setitem__(self, key: int, value: int) -> None:
raise RuntimeError()
def __contains__(self, x: int) -> bool:
raise RuntimeError()
def __len__(self) -> int:
return -5
def any_seq_error() -> Any:
return SeqError()
def test_set_item_error_propagate() -> None:
s = any_seq_error()
try:
s[44] = 66
except RuntimeError:
pass
else:
assert False
def test_contains_error_propagate() -> None:
s = any_seq_error()
try:
3 in s
except RuntimeError:
pass
else:
assert False
def test_negative_len() -> None:
try:
len(SeqError())
except ValueError:
pass
else:
assert False
class DelItemNoSetItem:
def __delitem__(self, x: int) -> None:
self.key = x
def test_del_item_with_no_set_item() -> None:
o = DelItemNoSetItem()
del o[22]
assert o.key == 22
a = o # type: Any
del a[12]
assert a.key == 12
try:
a[1] = 2
except TypeError as e:
assert str(e) == "'DelItemNoSetItem' object does not support item assignment"
else:
assert False
class SetItemOverride(dict):
# Only override __setitem__, __delitem__ comes from dict
def __setitem__(self, x: int, y: int) -> None:
self.key = x
self.value = y
def test_set_item_override() -> None:
o = SetItemOverride({'x': 12, 'y': 13})
o[2] = 3
assert o.key == 2 and o.value == 3
a = o # type: Any
o[4] = 5
assert o.key == 4 and o.value == 5
assert o['x'] == 12
assert o['y'] == 13
del o['x']
assert 'x' not in o and 'y' in o
del a['y']
assert 'y' not in a and 'x' not in a
class DelItemOverride(dict):
# Only override __delitem__, __setitem__ comes from dict
def __delitem__(self, x: int) -> None:
self.key = x
def test_del_item_override() -> None:
o = DelItemOverride()
del o[2]
assert o.key == 2
a = o # type: Any
del o[5]
assert o.key == 5
o['x'] = 12
assert o['x'] == 12
a['y'] = 13
assert a['y'] == 13
class SetItemOverrideNative(Seq):
def __setitem__(self, key: int, value: int) -> None:
self.key = key + 1
self.value = value + 1
def test_native_set_item_override() -> None:
o = SetItemOverrideNative()
o[1] = 4
assert o.key == 2 and o.value == 5
del o[6]
assert o.key == 6
a = o # type: Any
a[10] = 12
assert a.key == 11 and a.value == 13
del a[16]
assert a.key == 16
class DelItemOverrideNative(Seq):
def __delitem__(self, key: int) -> None:
self.key = key + 2
def test_native_del_item_override() -> None:
o = DelItemOverrideNative()
o[1] = 4
assert o.key == 1 and o.value == 4
del o[6]
assert o.key == 8
a = o # type: Any
a[10] = 12
assert a.key == 10 and a.value == 12
del a[16]
assert a.key == 18
[case testDundersNumber]
from typing import Any
class C:
def __init__(self, x: int) -> None:
self.x = x
def __neg__(self) -> int:
return self.x + 1
def __invert__(self) -> int:
return self.x + 2
def __int__(self) -> int:
return self.x + 3
def __float__(self) -> float:
return float(self.x + 4)
def __pos__(self) -> int:
return self.x + 5
def __abs__(self) -> int:
return abs(self.x) + 6
def test_unary_dunders_generic() -> None:
a: Any = C(10)
assert -a == 11
assert ~a == 12
assert int(a) == 13
assert float(a) == 14.0
assert +a == 15
assert abs(a) == 16
def test_unary_dunders_native() -> None:
c = C(10)
assert -c == 11
assert ~c == 12
assert int(c) == 13
assert float(c) == 14.0
assert +c == 15
assert abs(c) == 16
[case testDundersBinarySimple]
from typing import Any
class C:
def __init__(self) -> None:
self.x = 5
def __add__(self, y: int) -> int:
return self.x + y
def __sub__(self, y: int) -> int:
return self.x - y
def __mul__(self, y: int) -> int:
return self.x * y
def __mod__(self, y: int) -> int:
return self.x % y
def __lshift__(self, y: int) -> int:
return self.x << y
def __rshift__(self, y: int) -> int:
return self.x >> y
def __and__(self, y: int) -> int:
return self.x & y
def __or__(self, y: int) -> int:
return self.x | y
def __xor__(self, y: int) -> int:
return self.x ^ y
def __matmul__(self, y: int) -> int:
return self.x + y + 10
def __truediv__(self, y: int) -> int:
return self.x + y + 20
def __floordiv__(self, y: int) -> int:
return self.x + y + 30
def __divmod__(self, y: int) -> int:
return self.x + y + 40
def __pow__(self, y: int) -> int:
return self.x + y + 50
def test_generic() -> None:
a: Any = C()
assert a + 3 == 8
assert a - 3 == 2
assert a * 5 == 25
assert a % 2 == 1
assert a << 4 == 80
assert a >> 0 == 5
assert a >> 1 == 2
assert a & 1 == 1
assert a | 3 == 7
assert a ^ 3 == 6
assert a @ 3 == 18
assert a / 2 == 27
assert a // 2 == 37
assert divmod(a, 2) == 47
assert a ** 2 == 57
def test_native() -> None:
c = C()
assert c + 3 == 8
assert c - 3 == 2
assert divmod(c, 3) == 48
assert c ** 3 == 58
def test_error() -> None:
a: Any = C()
try:
a + 'x'
except TypeError as e:
assert str(e) == "unsupported operand type(s) for +: 'C' and 'str'"
else:
assert False
try:
a - 'x'
except TypeError as e:
assert str(e) == "unsupported operand type(s) for -: 'C' and 'str'"
else:
assert False
try:
a ** 'x'
except TypeError as e:
assert str(e) == "unsupported operand type(s) for **: 'C' and 'str'"
else:
assert False
[case testDundersBinaryReverse]
from typing import Any
class C:
def __init__(self) -> None:
self.x = 5
def __add__(self, y: int) -> int:
return self.x + y
def __radd__(self, y: int) -> int:
return self.x + y + 1
def __sub__(self, y: int) -> int:
return self.x - y
def __rsub__(self, y: int) -> int:
return self.x - y - 1
def __pow__(self, y: int) -> int:
return self.x**y
def __rpow__(self, y: int) -> int:
return self.x**y + 1
def test_generic() -> None:
a: Any = C()
assert a + 3 == 8
assert 4 + a == 10
assert a - 3 == 2
assert 4 - a == 0
assert a**3 == 125
assert 4**a == 626
def test_native() -> None:
c = C()
assert c + 3 == 8
assert 4 + c == 10
assert c - 3 == 2
assert 4 - c == 0
assert c**3 == 125
assert 4**c == 626
def test_errors() -> None:
a: Any = C()
try:
a + 'x'
except TypeError as e:
assert str(e) == "unsupported operand type(s) for +: 'C' and 'str'"
else:
assert False
try:
a - 'x'
except TypeError as e:
assert str(e) == "unsupported operand type(s) for -: 'C' and 'str'"
else:
assert False
try:
'x' + a
except TypeError as e:
assert str(e) in ('can only concatenate str (not "C") to str',
'must be str, not C')
else:
assert False
try:
'x' ** a
except TypeError as e:
assert str(e) == "unsupported operand type(s) for ** or pow(): 'str' and 'C'"
else:
assert False
class F:
def __add__(self, x: int) -> int:
return 5
def __pow__(self, x: int) -> int:
return -5
class G:
def __add__(self, x: int) -> int:
return 33
def __pow__(self, x: int) -> int:
return -33
def __radd__(self, x: F) -> int:
return 6
def __rpow__(self, x: F) -> int:
return -6
def test_type_mismatch_fall_back_to_reverse() -> None:
assert F() + G() == 6
assert F()**G() == -6
[case testDundersBinaryNotImplemented]
# mypy: allow-untyped-defs
from typing import Any, Union
from testutil import assertRaises
class C:
def __init__(self, v: int) -> None:
self.v = v
def __add__(self, y: int) -> Union[int, Any]:
if y == 1:
return self.v
return NotImplemented
def test_any_add() -> None:
a: Any = C(4)
assert a + 1 == 4
try:
a + 2
except TypeError:
pass
else:
assert False
class D:
def __init__(self, x: int) -> None:
self.x = x
def __add__(self, e: E) -> Union[int, Any]:
if e.x == 1:
return 2
return NotImplemented
class E:
def __init__(self, x: int) -> None:
self.x = x
def __radd__(self, d: D) -> Union[int, Any]:
if d.x == 3:
return 4
return NotImplemented
def test_any_radd() -> None:
d1: Any = D(1)
d3: Any = D(3)
e1: Any = E(1)
e3: Any = E(3)
assert d1 + e1 == 2
assert d3 + e1 == 2
assert d3 + e3 == 4
class F:
def __init__(self, v):
self.v = v
def __add__(self, x):
if isinstance(x, int):
return self.v + x
return NotImplemented
class G:
def __radd__(self, x):
if isinstance(x, F):
return x.v + 1
if isinstance(x, str):
return 'a'
return NotImplemented
def test_unannotated_add() -> None:
o = F(4)
assert o + 5 == 9
with assertRaises(TypeError, "unsupported operand type(s) for +: 'F' and 'str'"):
o + 'x'
o2: Any = F(4)
assert o2 + 5 == 9
with assertRaises(TypeError, "unsupported operand type(s) for +: 'F' and 'str'"):
o2 + 'x'
def test_unannotated_add_and_radd_1() -> None:
o = F(4)
assert o + G() == 5
o2: Any = F(4)
assert o2 + G() == 5
def test_unannotated_radd() -> None:
assert 'x' + G() == 'a'
with assertRaises(TypeError, "unsupported operand type(s) for +: 'int' and 'G'"):
1 + G()
o: Any = G()
assert 'x' + o == 'a'
with assertRaises(TypeError, "unsupported operand type(s) for +: 'int' and 'G'"):
1 + o
class H:
def __add__(self, x):
if isinstance(x, int):
return x + 1
return NotImplemented
def __radd__(self, x):
if isinstance(x, str):
return 22
return NotImplemented
def test_unannotated_add_and_radd_2() -> None:
h = H()
assert h + 5 == 6
assert 'x' + h == 22
with assertRaises(TypeError, "unsupported operand type(s) for +: 'int' and 'H'"):
1 + h
h2: Any = H()
assert h + 5 == 6
assert 'x' + h == 22
with assertRaises(TypeError, "unsupported operand type(s) for +: 'int' and 'H'"):
1 + h
# TODO: Inheritance
[case testDifferentReverseDunders]
from typing import Any
class C:
# __radd__ and __rsub__ are tested elsewhere
def __rmul__(self, x: Any) -> int:
return 1
def __rtruediv__(self, x: Any) -> int:
return 2
def __rmod__(self, x: Any) -> int:
return 3
def __rfloordiv__(self, x: Any) -> int:
return 4
def __rlshift__(self, x: Any) -> int:
return 5
def __rrshift__(self, x: Any) -> int:
return 6
def __rand__(self, x: Any) -> int:
return 7
def __ror__(self, x: Any) -> int:
return 8
def __rxor__(self, x: Any) -> int:
return 9
def __rmatmul__(self, x: Any) -> int:
return 10
def test_reverse_dunders() -> None:
x = 0
c = C()
assert x * c == 1
assert x / c == 2
assert x % c == 3
assert x // c == 4
assert x << c == 5
assert x >> c == 6
assert x & c == 7
assert x | c == 8
assert x ^ c == 9
assert x @ c == 10
[case testDundersInplace]
from typing import Any
from testutil import assertRaises
class C:
def __init__(self) -> None:
self.x = 5
def __iadd__(self, y: int) -> C:
self.x += y
return self
def __isub__(self, y: int) -> C:
self.x -= y
return self
def __imul__(self, y: int) -> C:
self.x *= y
return self
def __imod__(self, y: int) -> C:
self.x %= y
return self
def __itruediv__(self, y: int) -> C:
self.x += y + 10
return self
def __ifloordiv__(self, y: int) -> C:
self.x += y + 20
return self
def __ilshift__(self, y: int) -> C:
self.x <<= y
return self
def __irshift__(self, y: int) -> C:
self.x >>= y
return self
def __iand__(self, y: int) -> C:
self.x &= y
return self
def __ior__(self, y: int) -> C:
self.x |= y
return self
def __ixor__(self, y: int) -> C:
self.x ^= y
return self
def __imatmul__(self, y: int) -> C:
self.x += y + 5
return self
def __ipow__(self, y: int, __mod_throwaway: None = None) -> C:
self.x **= y
return self
def test_generic_1() -> None:
c: Any = C()
c += 3
assert c.x == 8
c -= 5
assert c.x == 3
c *= 3
assert c.x == 9
c %= 4
assert c.x == 1
c /= 5
assert c.x == 16
c //= 4
assert c.x == 40
c **= 2
assert c.x == 1600
def test_generic_2() -> None:
c: Any = C()
c <<= 4
assert c.x == 80
c >>= 3
assert c.x == 10
c &= 3
assert c.x == 2
c |= 6
assert c.x == 6
c ^= 12
assert c.x == 10
c @= 3
assert c.x == 18
def test_native() -> None:
c = C()
c += 3
assert c.x == 8
c -= 5
assert c.x == 3
c *= 3
assert c.x == 9
c **= 2
assert c.x == 81
def test_error() -> None:
c: Any = C()
with assertRaises(TypeError, "int object expected; got str"):
c += 'x'
class BadInplaceAdd:
def __init__(self) -> None:
self.x = 0
def __iadd__(self, x: int) -> Any:
self.x += x
def test_in_place_operator_returns_none() -> None:
o = BadInplaceAdd()
with assertRaises(TypeError, "native.BadInplaceAdd object expected; got None"):
o += 5
[case testDunderMinMax]
class SomeItem:
def __init__(self, val: int) -> None:
self.val = val
def __lt__(self, x: 'SomeItem') -> bool:
return self.val < x.val
def __gt__(self, x: 'SomeItem') -> bool:
return self.val > x.val
class AnotherItem:
def __init__(self, val: str) -> None:
self.val = val
def __lt__(self, x: 'AnotherItem') -> bool:
return True
def __gt__(self, x: 'AnotherItem') -> bool:
return True
def test_dunder_min() -> None:
x = SomeItem(5)
y = SomeItem(10)
z = SomeItem(15)
assert min(x, y).val == 5
assert min(y, z).val == 10
assert max(x, y).val == 10
assert max(y, z).val == 15
x2 = AnotherItem('xxx')
y2 = AnotherItem('yyy')
z2 = AnotherItem('zzz')
assert min(x2, y2).val == 'yyy'
assert min(y2, x2).val == 'xxx'
assert max(x2, y2).val == 'yyy'
assert max(y2, x2).val == 'xxx'
assert min(y2, z2).val == 'zzz'
assert max(x2, z2).val == 'zzz'
[case testDundersPowerSpecial]
import sys
from typing import Any, Optional
from testutil import assertRaises
class Forward:
def __pow__(self, exp: int, mod: Optional[int] = None) -> int:
if mod is None:
return 2**exp
else:
return 2**exp % mod
class ForwardModRequired:
def __pow__(self, exp: int, mod: int) -> int:
return 2**exp % mod
class ForwardNotImplemented:
def __pow__(self, exp: int, mod: Optional[object] = None) -> Any:
return NotImplemented
class Reverse:
def __rpow__(self, exp: int) -> int:
return 2**exp + 1
class Both:
def __pow__(self, exp: int, mod: Optional[int] = None) -> int:
if mod is None:
return 2**exp
else:
return 2**exp % mod
def __rpow__(self, exp: int) -> int:
return 2**exp + 1
class Child(ForwardNotImplemented):
def __rpow__(self, exp: object) -> int:
return 50
class Inplace:
value = 2
def __ipow__(self, exp: int, mod: Optional[int] = None) -> "Inplace":
self.value **= exp - (mod or 0)
return self
def test_native() -> None:
f = Forward()
assert f**3 == 8
assert pow(f, 3) == 8
assert pow(f, 3, 3) == 2
assert pow(ForwardModRequired(), 3, 3) == 2
b = Both()
assert b**3 == 8
assert 3**b == 9
assert pow(b, 3) == 8
assert pow(b, 3, 3) == 2
i = Inplace()
i **= 2
assert i.value == 4
def test_errors() -> None:
if sys.version_info[0] >= 3 and sys.version_info[1] >= 10:
op = "** or pow()"
else:
op = "pow()"
f = Forward()
with assertRaises(TypeError, f"unsupported operand type(s) for {op}: 'Forward', 'int', 'str'"):
pow(f, 3, "x") # type: ignore
with assertRaises(TypeError, "unsupported operand type(s) for **: 'Forward' and 'str'"):
f**"x" # type: ignore
r = Reverse()
with assertRaises(TypeError, "unsupported operand type(s) for ** or pow(): 'str' and 'Reverse'"):
"x"**r # type: ignore
with assertRaises(TypeError, f"unsupported operand type(s) for {op}: 'int', 'Reverse', 'int'"):
# Ternary pow() does not fallback to __rpow__ if LHS's __pow__ returns NotImplemented.
pow(3, r, 3) # type: ignore
with assertRaises(TypeError, f"unsupported operand type(s) for {op}: 'ForwardNotImplemented', 'Child', 'int'"):
# Ternary pow() does not try RHS's __rpow__ first when it's a subclass and redefines
# __rpow__ unlike other ops.
pow(ForwardNotImplemented(), Child(), 3) # type: ignore
with assertRaises(TypeError, "unsupported operand type(s) for ** or pow(): 'ForwardModRequired' and 'int'"):
ForwardModRequired()**3 # type: ignore
[case testDundersWithFinal]
from typing import final
class A:
def __init__(self, x: int) -> None:
self.x = x
def __add__(self, y: int) -> int:
return self.x + y
def __lt__(self, x: 'A') -> bool:
return self.x < x.x
@final
class B(A):
def __add__(self, y: int) -> int:
return self.x + y + 1
def __lt__(self, x: 'A') -> bool:
return self.x < x.x + 1
def test_final() -> None:
a = A(5)
b = B(5)
assert a + 3 == 8
assert b + 3 == 9
assert (a < A(5)) is False
assert (b < A(5)) is True
[case testDundersEq]
class Eq:
def __init__(self, x: int) -> None:
self.x = x
def __eq__(self, other: object) -> bool:
if not isinstance(other, Eq):
return NotImplemented
return self.x == other.x