-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy pathbuiltins.jl
1655 lines (1377 loc) · 41.5 KB
/
builtins.jl
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
### object interface
"""
pyis(x, y)
True if `x` and `y` are the same Python object. Equivalent to `x is y` in Python.
"""
pyis(x, y) = @autopy x y getptr(x_) == getptr(y_)
export pyis
pyisnot(x, y) = !pyis(x, y)
"""
pyrepr(x)
Equivalent to `repr(x)` in Python.
"""
pyrepr(x) = pynew(errcheck(@autopy x C.PyObject_Repr(getptr(x_))))
pyrepr(::Type{String}, x) = (s = pyrepr(x); ans = pystr_asstring(s); pydel!(s); ans)
export pyrepr
"""
pyascii(x)
Equivalent to `ascii(x)` in Python.
"""
pyascii(x) = pynew(errcheck(@autopy x C.PyObject_ASCII(getptr(x_))))
pyascii(::Type{String}, x) = (s = pyascii(x); ans = pystr_asstring(s); pydel!(s); ans)
export pyascii
"""
pyhasattr(x, k)
Equivalent to `hasattr(x, k)` in Python.
Tests if `getattr(x, k)` raises an `AttributeError`.
"""
function pyhasattr(x, k)
ptr = @autopy x k C.PyObject_GetAttr(getptr(x_), getptr(k_))
if iserrset(ptr)
if errmatches(pybuiltins.AttributeError)
errclear()
return false
else
pythrow()
end
else
decref(ptr)
return true
end
end
# pyhasattr(x, k) = errcheck(@autopy x k C.PyObject_HasAttr(getptr(x_), getptr(k_))) == 1
export pyhasattr
"""
pygetattr(x, k, [d])
Equivalent to `getattr(x, k)` or `x.k` in Python.
If `d` is specified, it is returned if the attribute does not exist.
"""
pygetattr(x, k) = pynew(errcheck(@autopy x k C.PyObject_GetAttr(getptr(x_), getptr(k_))))
function pygetattr(x, k, d)
ptr = @autopy x k C.PyObject_GetAttr(getptr(x_), getptr(k_))
if iserrset(ptr)
if errmatches(pybuiltins.AttributeError)
errclear()
return d
else
pythrow()
end
else
return pynew(ptr)
end
end
export pygetattr
"""
pysetattr(x, k, v)
Equivalent to `setattr(x, k, v)` or `x.k = v` in Python.
"""
pysetattr(x, k, v) = (
errcheck(@autopy x k v C.PyObject_SetAttr(getptr(x_), getptr(k_), getptr(v_))); nothing
)
export pysetattr
"""
pydelattr(x, k)
Equivalent to `delattr(x, k)` or `del x.k` in Python.
"""
pydelattr(x, k) =
(errcheck(@autopy x k C.PyObject_SetAttr(getptr(x_), getptr(k_), C.PyNULL)); nothing)
export pydelattr
"""
pyissubclass(s, t)
Test if `s` is a subclass of `t`. Equivalent to `issubclass(s, t)` in Python.
"""
pyissubclass(s, t) =
errcheck(@autopy s t C.PyObject_IsSubclass(getptr(s_), getptr(t_))) == 1
export pyissubclass
"""
pyisinstance(x, t)
Test if `x` is of type `t`. Equivalent to `isinstance(x, t)` in Python.
"""
pyisinstance(x, t) =
errcheck(@autopy x t C.PyObject_IsInstance(getptr(x_), getptr(t_))) == 1
export pyisinstance
"""
pyhash(x)
Equivalent to `hash(x)` in Python, converted to an `Integer`.
"""
pyhash(x) = errcheck(@autopy x C.PyObject_Hash(getptr(x_)))
export pyhash
"""
pytruth(x)
The truthyness of `x`. Equivalent to `bool(x)` in Python, converted to a `Bool`.
"""
pytruth(x) = errcheck(@autopy x C.PyObject_IsTrue(getptr(x_))) == 1
export pytruth
"""
pynot(x)
The falsyness of `x`. Equivalent to `not x` in Python, converted to a `Bool`.
"""
pynot(x) = errcheck(@autopy x C.PyObject_Not(getptr(x_))) == 1
export pynot
"""
pylen(x)
The length of `x`. Equivalent to `len(x)` in Python, converted to an `Integer`.
"""
pylen(x) = errcheck(@autopy x C.PyObject_Length(getptr(x_)))
export pylen
"""
pyhasitem(x, k)
Test if `pygetitem(x, k)` raises a `KeyError` or `AttributeError`.
"""
function pyhasitem(x, k)
ptr = @autopy x k C.PyObject_GetItem(getptr(x_), getptr(k_))
if iserrset(ptr)
if errmatches(pybuiltins.KeyError) || errmatches(pybuiltins.IndexError)
errclear()
return false
else
pythrow()
end
else
decref(ptr)
return true
end
end
export pyhasitem
"""
pygetitem(x, k, [d])
Equivalent `x[k]` in Python.
If `d` is specified, it is returned if the item does not exist (i.e. if `x[k]` raises a
`KeyError` or `IndexError`).
"""
pygetitem(x, k) = pynew(errcheck(@autopy x k C.PyObject_GetItem(getptr(x_), getptr(k_))))
function pygetitem(x, k, d)
ptr = @autopy x k C.PyObject_GetItem(getptr(x_), getptr(k_))
if iserrset(ptr)
if errmatches(pybuiltins.KeyError) || errmatches(pybuiltins.IndexError)
errclear()
return d
else
pythrow()
end
else
return pynew(ptr)
end
end
export pygetitem
"""
pysetitem(x, k, v)
Equivalent to `setitem(x, k, v)` or `x[k] = v` in Python.
"""
pysetitem(x, k, v) = (
errcheck(@autopy x k v C.PyObject_SetItem(getptr(x_), getptr(k_), getptr(v_))); nothing
)
export pysetitem
"""
pydelitem(x, k)
Equivalent to `delitem(x, k)` or `del x[k]` in Python.
"""
pydelitem(x, k) =
(errcheck(@autopy x k C.PyObject_DelItem(getptr(x_), getptr(k_))); nothing)
export pydelitem
"""
pydir(x)
Equivalent to `dir(x)` in Python.
"""
pydir(x) = pynew(errcheck(@autopy x C.PyObject_Dir(getptr(x_))))
export pydir
pycallargs(f) = pynew(errcheck(@autopy f C.PyObject_CallObject(getptr(f_), C.PyNULL)))
pycallargs(f, args) =
pynew(errcheck(@autopy f args C.PyObject_CallObject(getptr(f_), getptr(args_))))
pycallargs(f, args, kwargs) = pynew(
errcheck(
@autopy f args kwargs C.PyObject_Call(getptr(f_), getptr(args_), getptr(kwargs_))
),
)
"""
pycall(f, args...; kwargs...)
Call the Python object `f` with the given arguments.
"""
pycall(f, args...; kwargs...) =
if !isempty(kwargs)
args_ = pytuple_fromiter(args)
kwargs_ = pystrdict_fromiter(kwargs)
ans = pycallargs(f, args_, kwargs_)
pydel!(args_)
pydel!(kwargs_)
ans
elseif !isempty(args)
args_ = pytuple_fromiter(args)
ans = pycallargs(f, args_)
pydel!(args_)
ans
else
pycallargs(f)
end
export pycall
"""
pyeq(x, y)
pyeq(Bool, x, y)
Equivalent to `x == y` in Python. The second form converts to `Bool`.
"""
pyeq(x, y) =
pynew(errcheck(@autopy x y C.PyObject_RichCompare(getptr(x_), getptr(y_), C.Py_EQ)))
"""
pyne(x, y)
pyne(Bool, x, y)
Equivalent to `x != y` in Python. The second form converts to `Bool`.
"""
pyne(x, y) =
pynew(errcheck(@autopy x y C.PyObject_RichCompare(getptr(x_), getptr(y_), C.Py_NE)))
"""
pyle(x, y)
pyle(Bool, x, y)
Equivalent to `x <= y` in Python. The second form converts to `Bool`.
"""
pyle(x, y) =
pynew(errcheck(@autopy x y C.PyObject_RichCompare(getptr(x_), getptr(y_), C.Py_LE)))
"""
pylt(x, y)
pylt(Bool, x, y)
Equivalent to `x < y` in Python. The second form converts to `Bool`.
"""
pylt(x, y) =
pynew(errcheck(@autopy x y C.PyObject_RichCompare(getptr(x_), getptr(y_), C.Py_LT)))
"""
pyge(x, y)
pyge(Bool, x, y)
Equivalent to `x >= y` in Python. The second form converts to `Bool`.
"""
pyge(x, y) =
pynew(errcheck(@autopy x y C.PyObject_RichCompare(getptr(x_), getptr(y_), C.Py_GE)))
"""
pygt(x, y)
pygt(Bool, x, y)
Equivalent to `x > y` in Python. The second form converts to `Bool`.
"""
pygt(x, y) =
pynew(errcheck(@autopy x y C.PyObject_RichCompare(getptr(x_), getptr(y_), C.Py_GT)))
pyeq(::Type{Bool}, x, y) =
errcheck(@autopy x y C.PyObject_RichCompareBool(getptr(x_), getptr(y_), C.Py_EQ)) == 1
pyne(::Type{Bool}, x, y) =
errcheck(@autopy x y C.PyObject_RichCompareBool(getptr(x_), getptr(y_), C.Py_NE)) == 1
pyle(::Type{Bool}, x, y) =
errcheck(@autopy x y C.PyObject_RichCompareBool(getptr(x_), getptr(y_), C.Py_LE)) == 1
pylt(::Type{Bool}, x, y) =
errcheck(@autopy x y C.PyObject_RichCompareBool(getptr(x_), getptr(y_), C.Py_LT)) == 1
pyge(::Type{Bool}, x, y) =
errcheck(@autopy x y C.PyObject_RichCompareBool(getptr(x_), getptr(y_), C.Py_GE)) == 1
pygt(::Type{Bool}, x, y) =
errcheck(@autopy x y C.PyObject_RichCompareBool(getptr(x_), getptr(y_), C.Py_GT)) == 1
export pyeq, pyne, pyle, pylt, pyge, pygt
"""
pycontains(x, v)
Equivalent to `v in x` in Python.
"""
pycontains(x, v) = errcheck(@autopy x v C.PySequence_Contains(getptr(x_), getptr(v_))) == 1
export pycontains
"""
pyin(v, x)
Equivalent to `v in x` in Python.
"""
pyin(v, x) = pycontains(x, v)
export pyin
pynotin(v, x) = !pyin(v, x)
### number interface
# unary
"""
pyneg(x)
Equivalent to `-x` in Python.
"""
pyneg(x) = pynew(errcheck(@autopy x C.PyNumber_Negative(getptr(x_))))
"""
pypos(x)
Equivalent to `+x` in Python.
"""
pypos(x) = pynew(errcheck(@autopy x C.PyNumber_Positive(getptr(x_))))
"""
pyabs(x)
Equivalent to `abs(x)` in Python.
"""
pyabs(x) = pynew(errcheck(@autopy x C.PyNumber_Absolute(getptr(x_))))
"""
pyinv(x)
Equivalent to `~x` in Python.
"""
pyinv(x) = pynew(errcheck(@autopy x C.PyNumber_Invert(getptr(x_))))
"""
pyindex(x)
Convert `x` losslessly to an `int`.
"""
pyindex(x) = pynew(errcheck(@autopy x C.PyNumber_Index(getptr(x_))))
export pyneg, pypos, pyabs, pyinv, pyindex
# binary
"""
pyadd(x, y)
Equivalent to `x + y` in Python.
"""
pyadd(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Add(getptr(x_), getptr(y_))))
"""
pysub(x, y)
Equivalent to `x - y` in Python.
"""
pysub(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Subtract(getptr(x_), getptr(y_))))
"""
pymul(x, y)
Equivalent to `x * y` in Python.
"""
pymul(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Multiply(getptr(x_), getptr(y_))))
"""
pymatmul(x, y)
Equivalent to `x @ y` in Python.
"""
pymatmul(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_MatrixMultiply(getptr(x_), getptr(y_))))
"""
pyfloordiv(x, y)
Equivalent to `x // y` in Python.
"""
pyfloordiv(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_FloorDivide(getptr(x_), getptr(y_))))
"""
pytruediv(x, y)
Equivalent to `x / y` in Python.
"""
pytruediv(x, y) = pynew(errcheck(@autopy x y C.PyNumber_TrueDivide(getptr(x_), getptr(y_))))
"""
pymod(x, y)
Equivalent to `x % y` in Python.
"""
pymod(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Remainder(getptr(x_), getptr(y_))))
"""
pydivmod(x, y)
Equivalent to `divmod(x, y)` in Python.
"""
pydivmod(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Divmod(getptr(x_), getptr(y_))))
"""
pylshift(x, y)
Equivalent to `x << y` in Python.
"""
pylshift(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Lshift(getptr(x_), getptr(y_))))
"""
pyrshift(x, y)
Equivalent to `x >> y` in Python.
"""
pyrshift(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Rshift(getptr(x_), getptr(y_))))
"""
pyand(x, y)
Equivalent to `x & y` in Python.
"""
pyand(x, y) = pynew(errcheck(@autopy x y C.PyNumber_And(getptr(x_), getptr(y_))))
"""
pyxor(x, y)
Equivalent to `x ^ y` in Python.
"""
pyxor(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Xor(getptr(x_), getptr(y_))))
"""
pyor(x, y)
Equivalent to `x | y` in Python.
"""
pyor(x, y) = pynew(errcheck(@autopy x y C.PyNumber_Or(getptr(x_), getptr(y_))))
export pyadd,
pysub,
pymul,
pymatmul,
pyfloordiv,
pytruediv,
pymod,
pydivmod,
pylshift,
pyrshift,
pyand,
pyxor,
pyor
# binary in-place
"""
pyiadd(x, y)
In-place add. `x = pyiadd(x, y)` is equivalent to `x += y` in Python.
"""
pyiadd(x, y) = pynew(errcheck(@autopy x y C.PyNumber_InPlaceAdd(getptr(x_), getptr(y_))))
"""
pyisub(x, y)
In-place subtract. `x = pyisub(x, y)` is equivalent to `x -= y` in Python.
"""
pyisub(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceSubtract(getptr(x_), getptr(y_))))
"""
pyimul(x, y)
In-place multiply. `x = pyimul(x, y)` is equivalent to `x *= y` in Python.
"""
pyimul(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceMultiply(getptr(x_), getptr(y_))))
"""
pyimatmul(x, y)
In-place matrix multiply. `x = pyimatmul(x, y)` is equivalent to `x @= y` in Python.
"""
pyimatmul(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceMatrixMultiply(getptr(x_), getptr(y_))))
"""
pyifloordiv(x, y)
In-place floor divide. `x = pyifloordiv(x, y)` is equivalent to `x //= y` in Python.
"""
pyifloordiv(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceFloorDivide(getptr(x_), getptr(y_))))
"""
pyitruediv(x, y)
In-place true division. `x = pyitruediv(x, y)` is equivalent to `x /= y` in Python.
"""
pyitruediv(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceTrueDivide(getptr(x_), getptr(y_))))
"""
pyimod(x, y)
In-place subtraction. `x = pyimod(x, y)` is equivalent to `x %= y` in Python.
"""
pyimod(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceRemainder(getptr(x_), getptr(y_))))
"""
pyilshift(x, y)
In-place left shift. `x = pyilshift(x, y)` is equivalent to `x <<= y` in Python.
"""
pyilshift(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceLshift(getptr(x_), getptr(y_))))
"""
pyirshift(x, y)
In-place right shift. `x = pyirshift(x, y)` is equivalent to `x >>= y` in Python.
"""
pyirshift(x, y) =
pynew(errcheck(@autopy x y C.PyNumber_InPlaceRshift(getptr(x_), getptr(y_))))
"""
pyiand(x, y)
In-place and. `x = pyiand(x, y)` is equivalent to `x &= y` in Python.
"""
pyiand(x, y) = pynew(errcheck(@autopy x y C.PyNumber_InPlaceAnd(getptr(x_), getptr(y_))))
"""
pyixor(x, y)
In-place xor. `x = pyixor(x, y)` is equivalent to `x ^= y` in Python.
"""
pyixor(x, y) = pynew(errcheck(@autopy x y C.PyNumber_InPlaceXor(getptr(x_), getptr(y_))))
"""
pyior(x, y)
In-place or. `x = pyior(x, y)` is equivalent to `x |= y` in Python.
"""
pyior(x, y) = pynew(errcheck(@autopy x y C.PyNumber_InPlaceOr(getptr(x_), getptr(y_))))
export pyiadd,
pyisub,
pyimul,
pyimatmul,
pyifloordiv,
pyitruediv,
pyimod,
pyilshift,
pyirshift,
pyiand,
pyixor,
pyior
# power
"""
pypow(x, y, z=None)
Equivalent to `x ** y` or `pow(x, y, z)` in Python.
"""
pypow(x, y, z = pybuiltins.None) =
pynew(errcheck(@autopy x y z C.PyNumber_Power(getptr(x_), getptr(y_), getptr(z_))))
"""
pyipow(x, y, z=None)
In-place power. `x = pyipow(x, y)` is equivalent to `x **= y` in Python.
"""
pyipow(x, y, z = pybuiltins.None) = pynew(
errcheck(@autopy x y z C.PyNumber_InPlacePower(getptr(x_), getptr(y_), getptr(z_))),
)
export pypow, pyipow
### iter
"""
pyiter(x)
Equivalent to `iter(x)` in Python.
"""
pyiter(x) = pynew(errcheck(@autopy x C.PyObject_GetIter(getptr(x_))))
export pyiter
"""
pynext(x)
Equivalent to `next(x)` in Python.
"""
pynext(x) = pybuiltins.next(x)
export pynext
"""
unsafe_pynext(x)
Return the next item in the iterator `x`. When there are no more items, return NULL.
"""
unsafe_pynext(x::Py) = Base.GC.@preserve x pynew(errcheck_ambig(C.PyIter_Next(getptr(x))))
### None
pyisnone(x) = pyis(x, pybuiltins.None)
### bool
"""
pybool(x)
Convert `x` to a Python `bool`.
"""
pybool(x::Bool = false) = pynew(x ? pybuiltins.True : pybuiltins.False)
pybool(x::Number) = pybool(!iszero(x))
pybool(x) = pybuiltins.bool(x)
export pybool
pyisTrue(x) = pyis(x, pybuiltins.True)
pyisFalse(x) = pyis(x, pybuiltins.False)
pyisbool(x) = pyisTrue(x) || pyisFalse(x)
function pybool_asbool(x)
@autopy x if pyisTrue(x_)
true
elseif pyisFalse(x_)
false
else
error("not a bool")
end
end
### str
pystr_fromUTF8(x::Ptr, n::Integer) = pynew(errcheck(C.PyUnicode_DecodeUTF8(x, n, C_NULL)))
pystr_fromUTF8(x) = pystr_fromUTF8(pointer(x), sizeof(x))
"""
pystr(x)
Convert `x` to a Python `str`.
"""
pystr(x) = pynew(errcheck(@autopy x C.PyObject_Str(getptr(x_))))
pystr(x::String) = pystr_fromUTF8(x)
pystr(x::SubString{String}) = pystr_fromUTF8(x)
pystr(x::Char) = pystr(string(x))
pystr(::Type{String}, x) = (s = pystr(x); ans = pystr_asstring(s); pydel!(s); ans)
export pystr
pystr_asUTF8bytes(x::Py) =
Base.GC.@preserve x pynew(errcheck(C.PyUnicode_AsUTF8String(getptr(x))))
pystr_asUTF8vector(x::Py) =
(b = pystr_asUTF8bytes(x); ans = pybytes_asvector(b); pydel!(b); ans)
pystr_asstring(x::Py) =
(b = pystr_asUTF8bytes(x); ans = pybytes_asUTF8string(b); pydel!(b); ans)
function pystr_intern!(x::Py)
ptr = Ref(getptr(x))
C.PyUnicode_InternInPlace(ptr)
setptr!(x, ptr[])
end
pyisstr(x) = pytypecheckfast(x, C.Py_TPFLAGS_UNICODE_SUBCLASS)
### bytes
pybytes_fromdata(x::Ptr, n::Integer) = pynew(errcheck(C.PyBytes_FromStringAndSize(x, n)))
pybytes_fromdata(x) = pybytes_fromdata(pointer(x), sizeof(x))
"""
pybytes(x)
Convert `x` to a Python `bytes`.
"""
pybytes(x) = pynew(errcheck(@autopy x C.PyObject_Bytes(getptr(x_))))
pybytes(x::Vector{UInt8}) = pybytes_fromdata(x)
pybytes(x::Base.CodeUnits{UInt8,String}) = pybytes_fromdata(x)
pybytes(x::Base.CodeUnits{UInt8,SubString{String}}) = pybytes_fromdata(x)
pybytes(::Type{T}, x) where {Vector{UInt8} <: T <: Vector} =
(b = pybytes(x); ans = pybytes_asvector(b); pydel!(b); ans)
pybytes(::Type{T}, x) where {Base.CodeUnits{UInt8,String} <: T <: Base.CodeUnits} =
(b = pybytes(x); ans = Base.CodeUnits(pybytes_asUTF8string(b)); pydel!(b); ans)
export pybytes
pyisbytes(x) = pytypecheckfast(x, C.Py_TPFLAGS_BYTES_SUBCLASS)
function pybytes_asdata(x::Py)
ptr = Ref(Ptr{Cchar}(0))
len = Ref(C.Py_ssize_t(0))
Base.GC.@preserve x errcheck(C.PyBytes_AsStringAndSize(getptr(x), ptr, len))
ptr[], len[]
end
function pybytes_asvector(x::Py)
ptr, len = pybytes_asdata(x)
unsafe_wrap(Array, Ptr{UInt8}(ptr), len)
end
function pybytes_asUTF8string(x::Py)
ptr, len = pybytes_asdata(x)
unsafe_string(Ptr{UInt8}(ptr), len)
end
### int
pyint_fallback(
x::Union{Int8,Int16,Int32,Int64,Int128,UInt8,UInt16,UInt32,UInt64,UInt128,BigInt},
) = pynew(errcheck(C.PyLong_FromString(string(x, base = 32), C_NULL, 32)))
pyint_fallback(x::Integer) = pyint_fallback(BigInt(x))
"""
pyint(x=0)
Convert `x` to a Python `int`.
"""
function pyint(x::Integer = 0)
y = mod(x, Clonglong)
if x == y
pynew(errcheck(C.PyLong_FromLongLong(y)))
else
pyint_fallback(x)
end
end
function pyint(x::Unsigned)
y = mod(x, Culonglong)
if x == y
pynew(errcheck(C.PyLong_FromUnsignedLongLong(y)))
else
pyint_fallback(x)
end
end
pyint(x) = @autopy x pynew(errcheck(C.PyNumber_Long(getptr(x_))))
export pyint
pyisint(x) = pytypecheckfast(x, C.Py_TPFLAGS_LONG_SUBCLASS)
### float
"""
pyfloat(x=0.0)
Convert `x` to a Python `float`.
"""
pyfloat(x::Real = 0.0) = pynew(errcheck(C.PyFloat_FromDouble(x)))
pyfloat(x) = @autopy x pynew(errcheck(C.PyNumber_Float(getptr(x_))))
export pyfloat
pyisfloat(x) = pytypecheck(x, pybuiltins.float)
pyfloat_asdouble(x) = errcheck_ambig(@autopy x C.PyFloat_AsDouble(getptr(x_)))
### complex
"""
pycomplex(x=0.0)
pycomplex(re, im)
Convert `x` to a Python `complex`, or create one from given real and imaginary parts.
"""
pycomplex(x::Real = 0.0, y::Real = 0.0) = pynew(errcheck(C.PyComplex_FromDoubles(x, y)))
pycomplex(x::Complex) = pycomplex(real(x), imag(x))
pycomplex(x) = pybuiltins.complex(x)
pycomplex(x, y) = pybuiltins.complex(x, y)
export pycomplex
pyiscomplex(x) = pytypecheck(x, pybuiltins.complex)
function pycomplex_ascomplex(x)
c = @autopy x C.PyComplex_AsCComplex(getptr(x_))
c.real == -1 && c.imag == 0 && errcheck()
return Complex(c.real, c.imag)
end
### type
"""
pytype(x)
The Python `type` of `x`.
"""
pytype(x) = pynew(errcheck(@autopy x C.PyObject_Type(getptr(x_))))
export pytype
"""
pytype(name, bases, dict)
Create a new type. Equivalent to `type(name, bases, dict)` in Python.
If `bases` is not a Python object, it is converted to one using `pytuple`.
The `dict` may either by a Python object or a Julia iterable. In the latter case, each item
may either be a `name => value` pair or a Python object with a `__name__` attribute.
In order to use a Julia `Function` as an instance method, it must be wrapped into a Python
function with [`pyfunc`](@ref PythonCall.pyfunc). Similarly, see also [`pyclassmethod`](@ref PythonCall.pyclassmethod),
[`pystaticmethod`](@ref PythonCall.pystaticmethod) or [`pyproperty`](@ref PythonCall.pyproperty). In all these cases, the arguments passed
to the function always have type `Py`. See the example below.
# Example
```julia
Foo = pytype("Foo", (), [
"__module__" => "__main__",
pyfunc(
name = "__init__",
doc = \"\"\"
Specify x and y to store in the Foo.
If omitted, y defaults to None.
\"\"\",
function (self, x, y = nothing)
self.x = x
self.y = y
return
end,
),
pyfunc(
name = "__repr__",
self -> "Foo(\$(self.x), \$(self.y))",
),
pyclassmethod(
name = "frompair",
doc = "Construct a Foo from a tuple of length two.",
(cls, xy) -> cls(xy...),
),
pystaticmethod(
name = "hello",
doc = "Prints a friendly greeting.",
(name) -> println("Hello, \$name"),
),
"xy" => pyproperty(
doc = "A tuple of x and y.",
get = (self) -> (self.x, self.y),
set = function (self, xy)
(x, y) = xy
self.x = x
self.y = y
nothing
end,
),
])
```
"""
function pytype(name, bases, dict)
bases2 = ispy(bases) ? bases : pytuple(bases)
dict2 =
ispy(dict) ? dict :
pydict(ispy(item) ? (pygetattr(item, "__name__") => item) : item for item in dict)
pybuiltins.type(name, bases2, dict2)
end
pyistype(x) = pytypecheckfast(x, C.Py_TPFLAGS_TYPE_SUBCLASS)
pytypecheck(x, t) = (@autopy x t C.Py_TypeCheck(getptr(x_), getptr(t_))) == 1
pytypecheckfast(x, f) = (@autopy x C.Py_TypeCheckFast(getptr(x_), f)) == 1
### slice
"""
pyslice([start], stop, [step])
Construct a Python `slice`. Unspecified arguments default to `None`.
"""
pyslice(x, y, z = pybuiltins.None) =
pynew(errcheck(@autopy x y z C.PySlice_New(getptr(x_), getptr(y_), getptr(z_))))
pyslice(y) = pyslice(pybuiltins.None, y, pybuiltins.None)
export pyslice
pyisslice(x) = pytypecheck(x, pybuiltins.slice)
### range
"""
pyrange([[start], [stop]], [step])
Construct a Python `range`. Unspecified arguments default to `None`.
"""
pyrange(x, y, z) = pybuiltins.range(x, y, z)
pyrange(x, y) = pybuiltins.range(x, y)
pyrange(y) = pybuiltins.range(y)
export pyrange
pyrange_fromrange(x::AbstractRange) = pyrange(first(x), last(x) + sign(step(x)), step(x))
pyisrange(x) = pytypecheck(x, pybuiltins.range)
### tuple
pynulltuple(len) = pynew(errcheck(C.PyTuple_New(len)))
function pytuple_setitem(xs::Py, i, x)
errcheck(C.PyTuple_SetItem(getptr(xs), i, incref(getptr(Py(x)))))
return xs
end
function pytuple_getitem(xs::Py, i)
Base.GC.@preserve xs pynew(incref(errcheck(C.PyTuple_GetItem(getptr(xs), i))))
end
function pytuple_fromiter(xs)
sz = Base.IteratorSize(typeof(xs))
if sz isa Base.HasLength || sz isa Base.HasShape
# length known, e.g. Tuple, Pair, Vector
ans = pynulltuple(length(xs))
for (i, x) in enumerate(xs)
pytuple_setitem(ans, i - 1, x)
end
return ans
else
# length unknown
xs_ = pylist_fromiter(xs)
ans = pylist_astuple(xs_)
pydel!(xs_)
return ans
end
end
@generated function pytuple_fromiter(xs::Tuple)
n = length(xs.parameters)
code = []
push!(code, :(ans = pynulltuple($n)))
for i = 1:n
push!(code, :(pytuple_setitem(ans, $(i - 1), xs[$i])))
end
push!(code, :(return ans))
return Expr(:block, code...)
end
"""
pytuple(x=())
Convert `x` to a Python `tuple`.
If `x` is a Python object, this is equivalent to `tuple(x)` in Python.
Otherwise `x` must be iterable.
"""
pytuple() = pynulltuple(0)
pytuple(x) = ispy(x) ? pybuiltins.tuple(x) : pytuple_fromiter(x)
export pytuple
pyistuple(x) = pytypecheckfast(x, C.Py_TPFLAGS_TUPLE_SUBCLASS)
### list
pynulllist(len) = pynew(errcheck(C.PyList_New(len)))
function pylist_setitem(xs::Py, i, x)
errcheck(C.PyList_SetItem(getptr(xs), i, incref(getptr(Py(x)))))
return xs
end
pylist_append(xs::Py, x) = errcheck(@autopy x C.PyList_Append(getptr(xs), getptr(x_)))
pylist_astuple(x) = pynew(errcheck(@autopy x C.PyList_AsTuple(getptr(x_))))
function pylist_fromiter(xs)
sz = Base.IteratorSize(typeof(xs))
if sz isa Base.HasLength || sz isa Base.HasShape
# length known
ans = pynulllist(length(xs))
for (i, x) in enumerate(xs)
pylist_setitem(ans, i - 1, x)
end
return ans
else
# length unknown
ans = pynulllist(0)
for x in xs
pylist_append(ans, x)
end
return ans
end
end
"""
pylist(x=())
Convert `x` to a Python `list`.
If `x` is a Python object, this is equivalent to `list(x)` in Python.
Otherwise `x` must be iterable.
"""
pylist() = pynulllist(0)
pylist(x) = ispy(x) ? pybuiltins.list(x) : pylist_fromiter(x)
export pylist
"""
pycollist(x::AbstractArray)
Create a nested Python `list`-of-`list`s from the elements of `x`. For matrices, this is a list of columns.
"""
function pycollist(x::AbstractArray{T,N}) where {T,N}
N == 0 && return pynew(Py(x[]))
d = N
ax = axes(x, d)