cpython 0.5.0

Bindings to Python
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
#![allow(dead_code, unused_variables)]

use cpython::_detail::ffi;
use cpython::*;
use std::cell::{Cell, RefCell};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::{isize, iter, mem};

macro_rules! py_run {
    ($py:expr, $val:ident, $code:expr) => {{
        let d = PyDict::new($py);
        d.set_item($py, stringify!($val), &$val).unwrap();
        $py.run($code, None, Some(&d)).expect($code);
    }};
}

macro_rules! py_assert {
    ($py:expr, $val:ident, $assertion:expr) => {
        py_run!($py, $val, concat!("assert ", $assertion))
    };
}

macro_rules! py_expect_exception {
    ($py:expr, $val:ident, $code:expr, $err:ident) => {{
        let d = PyDict::new($py);
        d.set_item($py, stringify!($val), &$val).unwrap();
        let res = $py.run($code, None, Some(&d));
        let err = res.unwrap_err();
        if !err.matches($py, $py.get_type::<exc::$err>()) {
            panic!(format!("Expected {} but got {:?}", stringify!($err), err))
        }
    }};
}

py_class!(class EmptyClass |py| { });

#[test]
fn empty_class() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let typeobj = py.get_type::<EmptyClass>();
    // By default, don't allow creating instances from python.
    assert!(typeobj.call(py, NoArgs, None).is_err());

    py_assert!(py, typeobj, "typeobj.__name__ == 'EmptyClass'");
}

py_class!(class EmptyClassInModule |py| { });

#[test]
fn empty_class_in_module() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let module = PyModule::new(py, "test_module.nested").unwrap();
    module.add_class::<EmptyClassInModule>(py).unwrap();

    let ty = module.get(py, "EmptyClassInModule").unwrap();
    assert_eq!(
        ty.getattr(py, "__name__")
            .unwrap()
            .extract::<String>(py)
            .unwrap(),
        "EmptyClassInModule"
    );
    assert_eq!(
        ty.getattr(py, "__module__")
            .unwrap()
            .extract::<String>(py)
            .unwrap(),
        "test_module.nested"
    );
}

py_class!(class EmptyClassWithNew |py| {
    def __new__(_cls) -> PyResult<EmptyClassWithNew> {
        EmptyClassWithNew::create_instance(py)
    }
});

#[test]
fn empty_class_with_new() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let typeobj = py.get_type::<EmptyClassWithNew>();
    assert!(typeobj
        .call(py, NoArgs, None)
        .unwrap()
        .cast_into::<EmptyClassWithNew>(py)
        .is_ok());
}

py_class!(class NewWithOneArg |py| {
    data _data: i32;
    def __new__(_cls, arg: i32) -> PyResult<NewWithOneArg> {
        NewWithOneArg::create_instance(py, arg)
    }
});

#[test]
fn new_with_one_arg() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let typeobj = py.get_type::<NewWithOneArg>();
    let obj = typeobj
        .call(py, (42,), None)
        .unwrap()
        .cast_into::<NewWithOneArg>(py)
        .unwrap();
    assert_eq!(*obj._data(py), 42);
}

py_class!(class NewWithTwoArgs |py| {
    data _data1: i32;
    data _data2: i32;
    def __new__(_cls, arg1: i32, arg2: i32) -> PyResult<NewWithTwoArgs> {
        NewWithTwoArgs::create_instance(py, arg1, arg2)
    }
});

#[test]
fn new_with_two_args() {
    let gil = Python::acquire_gil();
    let py = gil.python();
    let typeobj = py.get_type::<NewWithTwoArgs>();
    let obj = typeobj
        .call(py, (10, 20), None)
        .unwrap()
        .cast_into::<NewWithTwoArgs>(py)
        .unwrap();
    assert_eq!(*obj._data1(py), 10);
    assert_eq!(*obj._data2(py), 20);
}

struct TestDropCall {
    drop_called: Arc<AtomicBool>,
}
impl Drop for TestDropCall {
    fn drop(&mut self) {
        self.drop_called.store(true, Ordering::Relaxed);
    }
}

py_class!(class DataIsDropped |py| {
    data member1: TestDropCall;
    data member2: TestDropCall;
});

#[test]
fn data_is_dropped() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let drop_called1 = Arc::new(AtomicBool::new(false));
    let drop_called2 = Arc::new(AtomicBool::new(false));
    let inst = DataIsDropped::create_instance(
        py,
        TestDropCall {
            drop_called: drop_called1.clone(),
        },
        TestDropCall {
            drop_called: drop_called2.clone(),
        },
    );
    assert!(drop_called1.load(Ordering::Relaxed) == false);
    assert!(drop_called2.load(Ordering::Relaxed) == false);
    drop(inst);
    assert!(drop_called1.load(Ordering::Relaxed) == true);
    assert!(drop_called2.load(Ordering::Relaxed) == true);
}

py_class!(class InstanceMethod |py| {
    data member: i32;

    def method(&self) -> PyResult<i32> {
        Ok(*self.member(py))
    }
});

#[test]
fn instance_method() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let obj = InstanceMethod::create_instance(py, 42).unwrap();
    assert!(obj.method(py).unwrap() == 42);
    let d = PyDict::new(py);
    d.set_item(py, "obj", obj).unwrap();
    py.run("assert obj.method() == 42", None, Some(&d)).unwrap();
}

py_class!(class InstanceMethodWithArgs |py| {
    data member: i32;

    def method(&self, multiplier: i32) -> PyResult<i32> {
        Ok(*self.member(py) * multiplier)
    }

    def r#match(&self, r#match: i32) -> PyResult<i32> {
        Ok(r#match)
    }
});

#[test]
fn instance_method_with_args() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let obj = InstanceMethodWithArgs::create_instance(py, 7).unwrap();
    assert!(obj.method(py, 6).unwrap() == 42);
    let d = PyDict::new(py);
    d.set_item(py, "obj", obj).unwrap();
    py.run("assert obj.method(3) == 21", None, Some(&d))
        .unwrap();
    py.run("assert obj.method(multiplier=6) == 42", None, Some(&d))
        .unwrap();
    py.run("assert obj.match(match=3) == 3", None, Some(&d))
        .unwrap();
}

py_class!(class ClassMethod |py| {
    def __new__(cls) -> PyResult<ClassMethod> {
        ClassMethod::create_instance(py)
    }

    @classmethod
    def method(cls) -> PyResult<String> {
        Ok(format!("{}.method()!", cls.name(py)))
    }
});

#[test]
fn class_method() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let d = PyDict::new(py);
    d.set_item(py, "C", py.get_type::<ClassMethod>()).unwrap();
    py.run(
        "assert C.method() == 'ClassMethod.method()!'",
        None,
        Some(&d),
    )
    .unwrap();
    py.run(
        "assert C().method() == 'ClassMethod.method()!'",
        None,
        Some(&d),
    )
    .unwrap();
}

py_class!(class ClassMethodWithArgs |py| {
    @classmethod
    def method(cls, input: &str) -> PyResult<String> {
        Ok(format!("{}.method({})", cls.name(py), input))
    }
});

#[test]
fn class_method_with_args() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let d = PyDict::new(py);
    d.set_item(py, "C", py.get_type::<ClassMethodWithArgs>())
        .unwrap();
    py.run(
        "assert C.method('abc') == 'ClassMethodWithArgs.method(abc)'",
        None,
        Some(&d),
    )
    .unwrap();
}

py_class!(class StaticMethod |py| {
    def __new__(cls) -> PyResult<StaticMethod> {
        StaticMethod::create_instance(py)
    }

    @staticmethod
    def method() -> PyResult<&'static str> {
        Ok("StaticMethod.method()!")
    }
});

#[test]
fn static_method() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    assert_eq!(StaticMethod::method(py).unwrap(), "StaticMethod.method()!");
    let d = PyDict::new(py);
    d.set_item(py, "C", py.get_type::<StaticMethod>()).unwrap();
    py.run(
        "assert C.method() == 'StaticMethod.method()!'",
        None,
        Some(&d),
    )
    .unwrap();
    py.run(
        "assert C().method() == 'StaticMethod.method()!'",
        None,
        Some(&d),
    )
    .unwrap();
}

py_class!(class StaticMethodWithArgs |py| {
    @staticmethod
    def method(input: i32) -> PyResult<String> {
        Ok(format!("0x{:x}", input))
    }
});

#[test]
fn static_method_with_args() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    assert_eq!(StaticMethodWithArgs::method(py, 1234).unwrap(), "0x4d2");
    let d = PyDict::new(py);
    d.set_item(py, "C", py.get_type::<StaticMethodWithArgs>())
        .unwrap();
    py.run("assert C.method(1337) == '0x539'", None, Some(&d))
        .unwrap();
}

py_class!(class StaticData |py| {
    static VAL1 = 123;
    static VAL2 = py.None();
});

#[test]
fn static_data() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let d = PyDict::new(py);
    d.set_item(py, "C", py.get_type::<StaticData>()).unwrap();
    py.run("assert C.VAL1 == 123", None, Some(&d)).unwrap();
    py.run("assert C.VAL2 is None", None, Some(&d)).unwrap();
    assert!(py.run("C.VAL1 = 124", None, Some(&d)).is_err());
}

py_class!(class GCIntegration |py| {
    data self_ref: RefCell<PyObject>;
    data dropped: TestDropCall;

    def __traverse__(&self, visit) {
        visit.call(&*self.self_ref(py).borrow())
    }

    def __clear__(&self) {
        let old_ref = mem::replace(&mut *self.self_ref(py).borrow_mut(), py.None());
        // Release reference only after the mutable borrow has expired.
        old_ref.release_ref(py);
    }
});

#[test]
fn gc_integration() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let drop_called = Arc::new(AtomicBool::new(false));
    let inst = GCIntegration::create_instance(
        py,
        RefCell::new(py.None()),
        TestDropCall {
            drop_called: drop_called.clone(),
        },
    )
    .unwrap();
    *inst.self_ref(py).borrow_mut() = inst.as_object().clone_ref(py);
    inst.release_ref(py);

    py.run("import gc; gc.collect()", None, None).unwrap();
    assert!(drop_called.load(Ordering::Relaxed));
}

py_class!(class Len |py| {
    data l: usize;

    def __len__(&self) -> PyResult<usize> {
        Ok(*self.l(py))
    }
});

#[test]
fn len() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let inst = Len::create_instance(py, 10).unwrap();
    py_assert!(py, inst, "len(inst) == 10");
    unsafe {
        assert_eq!(ffi::PyObject_Size(inst.as_object().as_ptr()), 10);
        assert_eq!(ffi::PyMapping_Size(inst.as_object().as_ptr()), 10);
    }

    let inst = Len::create_instance(py, (isize::MAX as usize) + 1).unwrap();
    py_expect_exception!(py, inst, "len(inst)", OverflowError);
}

py_class!(class Iterator |py| {
    data iter: RefCell<Box<dyn iter::Iterator<Item=i32> + Send>>;

    def __iter__(&self) -> PyResult<Iterator> {
        Ok(self.clone_ref(py))
    }

    def __next__(&self) -> PyResult<Option<i32>> {
        Ok(self.iter(py).borrow_mut().next())
    }
});

#[test]
fn iterator() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let inst = Iterator::create_instance(py, RefCell::new(Box::new(5..8))).unwrap();
    py_assert!(py, inst, "iter(inst) is inst");
    py_assert!(py, inst, "list(inst) == [5, 6, 7]");
}

py_class!(class StringMethods |py| {
    def __str__(&self) -> PyResult<&'static str> {
        Ok("str")
    }

    def __repr__(&self) -> PyResult<&'static str> {
        Ok("repr")
    }

    def __format__(&self, format_spec: &str) -> PyResult<String> {
        Ok(format!("format({})", format_spec))
    }

    def __unicode__(&self) -> PyResult<PyUnicode> {
        Ok(PyUnicode::new(py, "unicode"))
    }

    def __bytes__(&self) -> PyResult<PyBytes> {
        Ok(PyBytes::new(py, b"bytes"))
    }
});

#[test]
fn string_methods() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let obj = StringMethods::create_instance(py).unwrap();
    py_assert!(py, obj, "str(obj) == 'str'");
    py_assert!(py, obj, "repr(obj) == 'repr'");
    py_assert!(py, obj, "'{0:x}'.format(obj) == 'format(x)'");
}

#[test]
#[cfg(feature = "python27-sys")]
fn python2_string_methods() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let obj = StringMethods::create_instance(py).unwrap();
    py_assert!(py, obj, "unicode(obj) == u'unicode'");
}

#[test]
#[cfg(feature = "python3-sys")]
fn python3_string_methods() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let obj = StringMethods::create_instance(py).unwrap();
    py_assert!(py, obj, "bytes(obj) == b'bytes'");
}

py_class!(class Comparisons |py| {
    data val: i32;

    def __hash__(&self) -> PyResult<i32> {
        Ok(*self.val(py))
    }

    def __bool__(&self) -> PyResult<bool> {
        Ok(*self.val(py) != 0)
    }
});

#[test]
fn comparisons() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let zero = Comparisons::create_instance(py, 0).unwrap();
    let one = Comparisons::create_instance(py, 1).unwrap();
    let ten = Comparisons::create_instance(py, 10).unwrap();
    let minus_one = Comparisons::create_instance(py, -1).unwrap();
    py_assert!(py, one, "hash(one) == 1");
    py_assert!(py, ten, "hash(ten) == 10");
    py_assert!(py, minus_one, "hash(minus_one) == -2");

    py_assert!(py, one, "bool(one) is True");
    py_assert!(py, zero, "not zero");
}

py_class!(class Sequence |py| {
    def __len__(&self) -> PyResult<usize> {
        Ok(5)
    }

    def __getitem__(&self, key: PyObject) -> PyResult<PyObject> {
        if let Ok(index) = key.extract::<i32>(py) {
            if index == 5 {
                return Err(PyErr::new::<exc::IndexError, NoArgs>(py, NoArgs));
            }
        }
        Ok(key)
    }
});

#[test]
fn sequence() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = Sequence::create_instance(py).unwrap();
    py_assert!(py, c, "list(c) == [0, 1, 2, 3, 4]");
    py_assert!(py, c, "c['abc'] == 'abc'");
}

py_class!(class SequenceRef |py| {
    def __getitem__(&self, key: &str) -> PyResult<String> {
        if key.is_empty() {
            return Err(PyErr::new::<exc::IndexError, NoArgs>(py, NoArgs));
        }
        Ok(format!("Item for {}", key))
    }

    def __delitem__(&self, key: &str) -> PyResult<()> {
        if key.is_empty() {
            return Err(PyErr::new::<exc::IndexError, NoArgs>(py, NoArgs));
        }
        Ok(())
    }
});

#[test]
fn sequence_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = SequenceRef::create_instance(py).unwrap();
    py_assert!(py, c, "c['abc'] == 'Item for abc'");
    py_run!(py, c, "del c['abc']");
    py_expect_exception!(py, c, "c['']", IndexError);
    py_expect_exception!(py, c, "c[42]", TypeError);
    py_expect_exception!(py, c, "del c['']", IndexError);
}

py_class!(class Callable |py| {
    def __call__(&self, arg: i32) -> PyResult<i32> {
        Ok(arg * 6)
    }
});

#[test]
fn callable() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = Callable::create_instance(py).unwrap();
    py_assert!(py, c, "callable(c)");
    py_assert!(py, c, "c(7) == 42");

    let nc = Comparisons::create_instance(py, 0).unwrap();
    py_assert!(py, nc, "not callable(nc)");
}

py_class!(class SetItem |py| {
    data key: Cell<i32>;
    data val: Cell<i32>;

    def __setitem__(&self, key: i32, val: i32) -> PyResult<()> {
        self.key(py).set(key);
        self.val(py).set(val);
        Ok(())
    }
});

#[test]
fn setitem() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = SetItem::create_instance(py, Cell::new(0), Cell::new(0)).unwrap();
    py_run!(py, c, "c[1] = 2");
    assert_eq!(c.key(py).get(), 1);
    assert_eq!(c.val(py).get(), 2);
    py_expect_exception!(py, c, "del c[1]", NotImplementedError);
}

py_class!(class SetItemRef |py| {
    data key: RefCell<String>;
    data val: Cell<i32>;

    def __setitem__(&self, key: &str, val: i32) -> PyResult<()> {
        *self.key(py).borrow_mut() = key.to_string();
        self.val(py).set(val);
        Ok(())
    }
});

#[test]
fn setitem_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = SetItemRef::create_instance(py, RefCell::new(String::new()), Cell::new(0)).unwrap();
    py_run!(py, c, "c['foo'] = 100");
    assert_eq!(*c.key(py).borrow(), "foo");
    assert_eq!(c.val(py).get(), 100);
    py_expect_exception!(py, c, "c[None] = 1", TypeError);
}

py_class!(class SetItemOptRef |py| {
    data key: RefCell<String>;
    data val: Cell<i32>;

    def __setitem__(&self, key: Option<&str>, val: i32) -> PyResult<()> {
        if let Some(key) = key {
            *self.key(py).borrow_mut() = key.to_string();
            self.val(py).set(val);
            Ok(())
        } else {
            Err(PyErr::new::<exc::IndexError, NoArgs>(py, NoArgs))
        }
    }
});

#[test]
fn setitem_opt_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = SetItemOptRef::create_instance(py, RefCell::new(String::new()), Cell::new(0)).unwrap();
    py_run!(py, c, "c['foo'] = 100");
    assert_eq!(*c.key(py).borrow(), "foo");
    assert_eq!(c.val(py).get(), 100);
    py_expect_exception!(py, c, "c[None] = 1", IndexError);
}

py_class!(class DelItem |py| {
    data key: Cell<i32>;

    def __delitem__(&self, key: i32) -> PyResult<()> {
        self.key(py).set(key);
        Ok(())
    }
});

#[test]
fn delitem() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = DelItem::create_instance(py, Cell::new(0)).unwrap();
    py_run!(py, c, "del c[1]");
    assert_eq!(c.key(py).get(), 1);
    py_expect_exception!(py, c, "c[1] = 2", NotImplementedError);
}

py_class!(class SetDelItem |py| {
    data val: Cell<Option<i32>>;

    def __setitem__(&self, key: i32, val: i32) -> PyResult<()> {
        self.val(py).set(Some(val));
        Ok(())
    }

    def __delitem__(&self, key: i32) -> PyResult<()> {
        self.val(py).set(None);
        Ok(())
    }
});

#[test]
fn setdelitem() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = SetDelItem::create_instance(py, Cell::new(None)).unwrap();
    py_run!(py, c, "c[1] = 2");
    assert_eq!(c.val(py).get(), Some(2));
    py_run!(py, c, "del c[1]");
    assert_eq!(c.val(py).get(), None);
}

py_class!(class Reversed |py| {
    def __reversed__(&self) -> PyResult<&'static str> {
        Ok("I am reversed")
    }
});

#[test]
fn reversed() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = Reversed::create_instance(py).unwrap();
    py_run!(py, c, "assert reversed(c) == 'I am reversed'");
}

py_class!(class Contains |py| {
    def __contains__(&self, item: i32) -> PyResult<bool> {
        Ok(item >= 0)
    }
});

#[test]
fn contains() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = Contains::create_instance(py).unwrap();
    py_run!(py, c, "assert 1 in c");
    py_run!(py, c, "assert -1 not in c");
    py_run!(py, c, "assert 'wrong type' not in c");
}

py_class!(class ContainsRef |py| {
    def __contains__(&self, item: &str) -> PyResult<bool> {
        Ok(item.is_empty())
    }
});

#[test]
fn contains_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = ContainsRef::create_instance(py).unwrap();
    py_run!(py, c, "assert '' in c");
    py_run!(py, c, "assert 'hello' not in c");
    py_run!(py, c, "assert 42 not in c");
}

py_class!(class ContainsOptRef |py| {
    def __contains__(&self, item: Option<&str>) -> PyResult<bool> {
        Ok(item.map_or(false, str::is_empty))
    }
});

#[test]
fn contains_opt_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = ContainsOptRef::create_instance(py).unwrap();
    py_run!(py, c, "assert '' in c");
    py_run!(py, c, "assert 'hello' not in c");
    py_run!(py, c, "assert 42 not in c");
    py_run!(py, c, "assert None not in c");
}

py_class!(class UnaryArithmetic |py| {
    def __neg__(&self) -> PyResult<&'static str> {
        Ok("neg")
    }

    def __pos__(&self) -> PyResult<&'static str> {
        Ok("pos")
    }

    def __abs__(&self) -> PyResult<&'static str> {
        Ok("abs")
    }

    def __invert__(&self) -> PyResult<&'static str> {
        Ok("invert")
    }
});

#[test]
fn unary_arithmetic() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = UnaryArithmetic::create_instance(py).unwrap();
    py_run!(py, c, "assert -c == 'neg'");
    py_run!(py, c, "assert +c == 'pos'");
    py_run!(py, c, "assert abs(c) == 'abs'");
    py_run!(py, c, "assert ~c == 'invert'");
}

py_class!(class BinaryArithmetic |py| {
    def __repr__(&self) -> PyResult<&'static str> {
        Ok("BA")
    }

    def __add__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} + {:?}", lhs, rhs))
    }

    def __sub__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} - {:?}", lhs, rhs))
    }

    def __mul__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} * {:?}", lhs, rhs))
    }

    def __lshift__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} << {:?}", lhs, rhs))
    }

    def __rshift__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} >> {:?}", lhs, rhs))
    }

    def __and__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} & {:?}", lhs, rhs))
    }

    def __xor__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} ^ {:?}", lhs, rhs))
    }

    def __or__(lhs, rhs) -> PyResult<String> {
        Ok(format!("{:?} | {:?}", lhs, rhs))
    }
});

#[test]
fn binary_arithmetic() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = BinaryArithmetic::create_instance(py).unwrap();
    py_run!(py, c, "assert c + c == 'BA + BA'");
    py_run!(py, c, "assert c + 1 == 'BA + 1'");
    py_run!(py, c, "assert 1 + c == '1 + BA'");
    py_run!(py, c, "assert c - 1 == 'BA - 1'");
    py_run!(py, c, "assert 1 - c == '1 - BA'");
    py_run!(py, c, "assert c * 1 == 'BA * 1'");
    py_run!(py, c, "assert 1 * c == '1 * BA'");

    py_run!(py, c, "assert c << 1 == 'BA << 1'");
    py_run!(py, c, "assert 1 << c == '1 << BA'");
    py_run!(py, c, "assert c >> 1 == 'BA >> 1'");
    py_run!(py, c, "assert 1 >> c == '1 >> BA'");
    py_run!(py, c, "assert c & 1 == 'BA & 1'");
    py_run!(py, c, "assert 1 & c == '1 & BA'");
    py_run!(py, c, "assert c ^ 1 == 'BA ^ 1'");
    py_run!(py, c, "assert 1 ^ c == '1 ^ BA'");
    py_run!(py, c, "assert c | 1 == 'BA | 1'");
    py_run!(py, c, "assert 1 | c == '1 | BA'");
}

py_class!(class RichComparisons |py| {
    def __repr__(&self) -> PyResult<&'static str> {
        Ok("RC")
    }

    def __richcmp__(&self, other: &PyObject, op: CompareOp) -> PyResult<String> {
        match op {
            CompareOp::Lt => Ok(format!("{:?} < {:?}", self.as_object(), other)),
            CompareOp::Le => Ok(format!("{:?} <= {:?}", self.as_object(), other)),
            CompareOp::Eq => Ok(format!("{:?} == {:?}", self.as_object(), other)),
            CompareOp::Ne => Ok(format!("{:?} != {:?}", self.as_object(), other)),
            CompareOp::Gt => Ok(format!("{:?} > {:?}", self.as_object(), other)),
            CompareOp::Ge => Ok(format!("{:?} >= {:?}", self.as_object(), other))
        }
    }
});

py_class!(class RichComparisons2 |py| {
    def __repr__(&self) -> PyResult<&'static str> {
        Ok("RC2")
    }

    def __richcmp__(&self, other: &PyObject, op: CompareOp) -> PyResult<PyObject> {
        match op {
            CompareOp::Eq => Ok(true.to_py_object(py).into_object()),
            CompareOp::Ne => Ok(false.to_py_object(py).into_object()),
            _ => Ok(py.NotImplemented())
        }
    }
});

#[test]
fn rich_comparisons() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = RichComparisons::create_instance(py).unwrap();
    py_run!(py, c, "assert (c < c) == 'RC < RC'");
    py_run!(py, c, "assert (c < 1) == 'RC < 1'");
    py_run!(py, c, "assert (1 < c) == 'RC > 1'");
    py_run!(py, c, "assert (c <= c) == 'RC <= RC'");
    py_run!(py, c, "assert (c <= 1) == 'RC <= 1'");
    py_run!(py, c, "assert (1 <= c) == 'RC >= 1'");
    py_run!(py, c, "assert (c == c) == 'RC == RC'");
    py_run!(py, c, "assert (c == 1) == 'RC == 1'");
    py_run!(py, c, "assert (1 == c) == 'RC == 1'");
    py_run!(py, c, "assert (c != c) == 'RC != RC'");
    py_run!(py, c, "assert (c != 1) == 'RC != 1'");
    py_run!(py, c, "assert (1 != c) == 'RC != 1'");
    py_run!(py, c, "assert (c > c) == 'RC > RC'");
    py_run!(py, c, "assert (c > 1) == 'RC > 1'");
    py_run!(py, c, "assert (1 > c) == 'RC < 1'");
    py_run!(py, c, "assert (c >= c) == 'RC >= RC'");
    py_run!(py, c, "assert (c >= 1) == 'RC >= 1'");
    py_run!(py, c, "assert (1 >= c) == 'RC <= 1'");
}

#[test]
#[cfg(feature = "python3-sys")]
fn rich_comparisons_python_3_type_error() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c2 = RichComparisons2::create_instance(py).unwrap();
    py_expect_exception!(py, c2, "c2 < c2", TypeError);
    py_expect_exception!(py, c2, "c2 < 1", TypeError);
    py_expect_exception!(py, c2, "1 < c2", TypeError);
    py_expect_exception!(py, c2, "c2 <= c2", TypeError);
    py_expect_exception!(py, c2, "c2 <= 1", TypeError);
    py_expect_exception!(py, c2, "1 <= c2", TypeError);
    py_run!(py, c2, "assert (c2 == c2) == True");
    py_run!(py, c2, "assert (c2 == 1) == True");
    py_run!(py, c2, "assert (1 == c2) == True");
    py_run!(py, c2, "assert (c2 != c2) == False");
    py_run!(py, c2, "assert (c2 != 1) == False");
    py_run!(py, c2, "assert (1 != c2) == False");
    py_expect_exception!(py, c2, "c2 > c2", TypeError);
    py_expect_exception!(py, c2, "c2 > 1", TypeError);
    py_expect_exception!(py, c2, "1 > c2", TypeError);
    py_expect_exception!(py, c2, "c2 >= c2", TypeError);
    py_expect_exception!(py, c2, "c2 >= 1", TypeError);
    py_expect_exception!(py, c2, "1 >= c2", TypeError);
}

py_class!(class RichComparisonsRef |py| {
    def __repr__(&self) -> PyResult<&'static str> {
        Ok("RCR")
    }

    def __richcmp__(&self, other: &str, op: CompareOp) -> PyResult<bool> {
        match op {
            CompareOp::Lt => Ok("RCR" < other),
            CompareOp::Le => Ok("RCR" <= other),
            CompareOp::Eq => Ok("RCR" == other),
            CompareOp::Ne => Ok("RCR" != other),
            CompareOp::Gt => Ok("RCR" > other),
            CompareOp::Ge => Ok("RCR" >= other),
        }
    }
});

#[test]
fn rich_comparisons_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = RichComparisonsRef::create_instance(py).unwrap();
    py_assert!(py, c, "c < 'ZZZ'");
    py_assert!(py, c, "c <= 'ZZZ'");
    py_assert!(py, c, "c <= 'RCR'");
    py_assert!(py, c, "c == 'RCR'");
    py_assert!(py, c, "c != 'RRR'");
    py_assert!(py, c, "c > 'AAA'");
    py_assert!(py, c, "c >= 'AAA'");
    py_assert!(py, c, "c >= 'RCR'");
}

py_class!(class RichComparisonsOptRef |py| {
    def __repr__(&self) -> PyResult<&'static str> {
        Ok("RCR")
    }

    def __richcmp__(&self, other: Option<&str>, op: CompareOp) -> PyResult<bool> {
        match other {
            Some(other) => match op {
                CompareOp::Lt => Ok("RCR" < other),
                CompareOp::Le => Ok("RCR" <= other),
                CompareOp::Eq => Ok("RCR" == other),
                CompareOp::Ne => Ok("RCR" != other),
                CompareOp::Gt => Ok("RCR" > other),
                CompareOp::Ge => Ok("RCR" >= other),
            },
            None => match op {
                CompareOp::Ne | CompareOp::Gt | CompareOp::Ge => Ok(true),
                CompareOp::Eq | CompareOp::Lt | CompareOp::Le => Ok(false),
            },
        }
    }
});

#[test]
fn rich_comparisons_opt_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = RichComparisonsOptRef::create_instance(py).unwrap();
    py_assert!(py, c, "c != None");
    py_assert!(py, c, "c == 'RCR'");
    py_assert!(py, c, "c > None");
    py_assert!(py, c, "None <= c");
}

py_class!(class InPlaceOperations |py| {
    data value: Cell<u32>;

    def __repr__(&self) -> PyResult<String> {
        Ok(format!("IPO({:?})", self.value(py).get()))
    }

    def __iadd__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() + other);
        Ok(self.clone_ref(py))
    }

    def __isub__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() - other);
        Ok(self.clone_ref(py))
    }

    def __imul__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() * other);
        Ok(self.clone_ref(py))
    }

    def __ilshift__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() << other);
        Ok(self.clone_ref(py))
    }

    def __irshift__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() >> other);
        Ok(self.clone_ref(py))
    }

    def __iand__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() & other);
        Ok(self.clone_ref(py))
    }

    def __ixor__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() ^ other);
        Ok(self.clone_ref(py))
    }

    def __ior__(&self, other: u32) -> PyResult<Self> {
        self.value(py).set(self.value(py).get() | other);
        Ok(self.clone_ref(py))
    }
});

#[test]
fn inplace_operations() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = InPlaceOperations::create_instance(py, Cell::new(0)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c += 1; assert repr(c) == repr(d) == 'IPO(1)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(10)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c -= 1; assert repr(c) == repr(d) == 'IPO(9)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(3)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c *= 3; assert repr(c) == repr(d) == 'IPO(9)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(3)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c <<= 2; assert repr(c) == repr(d) == 'IPO(12)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(12)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c >>= 2; assert repr(c) == repr(d) == 'IPO(3)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(12)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c &= 10; assert repr(c) == repr(d) == 'IPO(8)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(12)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c |= 3; assert repr(c) == repr(d) == 'IPO(15)'"
    );

    let c = InPlaceOperations::create_instance(py, Cell::new(12)).unwrap();
    py_run!(
        py,
        c,
        "d = c; c ^= 5; assert repr(c) == repr(d) == 'IPO(9)'"
    );
}

py_class!(class InPlaceOperationsRef |py| {
    data value: RefCell<String>;

    def __repr__(&self) -> PyResult<String> {
        Ok(format!("IPOR({:?})", self.value(py).borrow()))
    }

    def __iadd__(&self, other: &str) -> PyResult<Self> {
        let mut value = self.value(py).borrow_mut();
        value.push_str(other);
        Ok(self.clone_ref(py))
    }
});

#[test]
fn inplace_operations_ref() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = InPlaceOperationsRef::create_instance(py, RefCell::new(String::new())).unwrap();
    py_run!(
        py,
        c,
        r#"d = c; c += "hello"; c += ", world"; assert repr(c) == repr(d) == 'IPOR("hello, world")'"#
    );
}

py_class!(class ContextManager |py| {
    data exit_called : Cell<bool>;

    def __enter__(&self) -> PyResult<i32> {
        Ok(42)
    }

    def __exit__(&self, ty: Option<PyType>, value: PyObject, traceback: PyObject) -> PyResult<bool> {
        self.exit_called(py).set(true);
        if ty == Some(py.get_type::<exc::ValueError>()) {
            Ok(true)
        } else {
            Ok(false)
        }
    }
});

#[test]
fn context_manager() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = ContextManager::create_instance(py, Cell::new(false)).unwrap();
    py_run!(py, c, "with c as x:\n  assert x == 42");
    assert!(c.exit_called(py).get());

    c.exit_called(py).set(false);
    py_run!(py, c, "with c as x:\n  raise ValueError");
    assert!(c.exit_called(py).get());

    c.exit_called(py).set(false);
    py_expect_exception!(
        py,
        c,
        "with c as x:\n  raise NotImplementedError",
        NotImplementedError
    );
    assert!(c.exit_called(py).get());
}

py_class!(class Properties |py| {
    data value: Cell<i32>;
    data value_by_ref: RefCell<String>;
    data value_by_opt_ref: RefCell<String>;

    def __repr__(&self) -> PyResult<String> {
        Ok(format!("P({:?} {:?} {:?})",
            self.value(py).get(),
            self.value_by_ref(py).borrow(),
            self.value_by_opt_ref(py).borrow()))
    }

    @property def prop(&self) -> PyResult<i32> {
        Ok(self.value(py).get())
    }

    @prop.setter def set_prop(&self, value: Option<i32>) -> PyResult<()> {
        self.value(py).set(value.unwrap_or(0));
        Ok(())
    }

    @property def prop_by_ref(&self) -> PyResult<String> {
        Ok(self.value_by_ref(py).borrow().to_string())
    }

    @prop_by_ref.setter def set_prop_by_ref(&self, value: Option<&str>) -> PyResult<()> {
        *self.value_by_ref(py).borrow_mut() = value.unwrap_or("DELETED").to_string();
        Ok(())
    }

    @property def prop_by_opt_ref(&self) -> PyResult<String> {
        Ok(self.value_by_opt_ref(py).borrow().to_string())
    }

    @prop_by_opt_ref.setter def set_prop_by_opt_ref(&self, value: Option<Option<&str>>) -> PyResult<()> {
        let value = value.unwrap_or(Some("DELETED")).unwrap_or("NO VALUE");
        *self.value_by_opt_ref(py).borrow_mut() = value.to_string();
        Ok(())
    }

    /// docs for match
    @property def r#match(&self) -> PyResult<bool> {
        Ok(self.value(py).get() != 0)
    }
});

#[test]
fn properties() {
    let gil = Python::acquire_gil();
    let py = gil.python();

    let c = Properties::create_instance(
        py,
        Cell::new(0),
        RefCell::new(String::new()),
        RefCell::new(String::new()),
    )
    .unwrap();

    py_run!(
        py,
        c,
        "assert 'docs for match' in c.__class__.match.__doc__"
    );

    py_run!(py, c, "assert c.prop == 0");
    py_run!(py, c, "assert not c.match");
    py_run!(py, c, "c.prop = 42");
    assert_eq!(c.value(py).get(), 42);
    py_run!(py, c, "assert c.match");
    assert!(c.r#match(py).unwrap());

    // Instead of really deleting, our setter sets back to 0
    py_run!(py, c, "delattr(c, 'prop')");
    py_run!(py, c, "assert c.prop == 0");

    py_run!(py, c, "c.prop_by_ref = 'testing'");
    py_run!(py, c, "assert c.prop_by_ref == 'testing'");

    py_run!(py, c, "c.prop_by_opt_ref = 'something'");
    assert_eq!(*c.value_by_opt_ref(py).borrow(), "something");
    py_run!(py, c, "c.prop_by_opt_ref = None");
    py_run!(py, c, "repr(c) == 'P(42, \"testing\" \"NO VALUE\")'");

    py_run!(py, c, "del c.prop_by_opt_ref");
    py_run!(py, c, "repr(c) == 'P(42, \"testing\" \"DELETED\")'");
}