-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathPython.swift
1284 lines (1101 loc) · 40.7 KB
/
Python.swift
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
//===-- Python.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file defines an interoperability layer for talking to Python from Swift.
//
//===----------------------------------------------------------------------===//
//
// The model provided by this file is completely dynamic and does not require
// invasive compiler support.
//
//===----------------------------------------------------------------------===//
import CPython
//===----------------------------------------------------------------------===//
// `PyReference` definition
//===----------------------------------------------------------------------===//
/// Typealias used when passing or returning a `PyObject` pointer with
/// implied ownership.
public typealias OwnedPyObjectPointer = UnsafeMutablePointer<PyObject>
/// A primitive reference to a Python C API `PyObject`.
///
/// A `PyReference` instance has ownership of its underlying `PyObject`, which
/// must be non-null.
///
// - Note: When Swift has ownership, `PyReference` should be removed.
// `PythonObject` will define copy constructors, move constructors, etc. to
// implement move semantics.
@usableFromInline @_fixed_layout
final class PyReference {
private var pointer: OwnedPyObjectPointer
init(owning pointer: OwnedPyObjectPointer) {
self.pointer = pointer
}
init(borrowing pointer: UnsafeMutablePointer<PyObject>) {
self.pointer = pointer
Py_IncRef(pointer)
}
deinit {
Py_DecRef(pointer)
}
var borrowedPyObject: UnsafeMutablePointer<PyObject> {
return pointer
}
var ownedPyObject: OwnedPyObjectPointer {
Py_IncRef(pointer)
return pointer
}
}
//===----------------------------------------------------------------------===//
// `PythonObject` definition
//===----------------------------------------------------------------------===//
// - Note: When Swift has ownership, `PythonObject` will define copy
// constructors, move constructors, etc. to implement move semantics.
/// `PythonObject` represents an object in Python and supports dynamic member
/// lookup. Any member access like `object.foo` will dynamically request the
/// Python runtime for a member with the specified name in this object.
///
/// `PythonObject` is passed to and returned from all Python function calls and
/// member references. It supports standard Python arithmetic and comparison
/// operators.
///
/// Internally, `PythonObject` is implemented as a reference-counted pointer to
/// a Python C API `PyObject`.
@dynamicCallable
@dynamicMemberLookup
@_fixed_layout
public struct PythonObject {
/// The underlying `PyReference`.
fileprivate var reference: PyReference
@usableFromInline
init(_ pointer: PyReference) {
reference = pointer
}
/// Creates a new instance, taking ownership of the specified `PyObject`
/// pointer.
public init(owning pointer: OwnedPyObjectPointer) {
reference = PyReference(owning: pointer)
}
/// Creates a new instance from the specified `PyObject` pointer.
public init(borrowing pointer: UnsafeMutablePointer<PyObject>) {
reference = PyReference(borrowing: pointer)
}
fileprivate var borrowedPyObject: UnsafeMutablePointer<PyObject> {
return reference.borrowedPyObject
}
fileprivate var ownedPyObject: OwnedPyObjectPointer {
return reference.ownedPyObject
}
}
/// Make `print(python)` print a pretty form of the `PythonObject`.
extension PythonObject : CustomStringConvertible {
/// A textual description of this `PythonObject`, produced by `Python.str`.
public var description: String {
// The `str` function is used here because it is designed to return
// human-readable descriptions of Python objects. The Python REPL also uses
// it for printing descriptions.
// `repr` is not used because it is not designed to be readable and takes
// too long for large objects.
return String(Python.str(self))!
}
}
// Make `PythonObject` show up nicely in the Xcode Playground results sidebar.
extension PythonObject : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
// Mirror representation, used by debugger/REPL.
extension PythonObject : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [], displayStyle: .struct)
}
}
//===----------------------------------------------------------------------===//
// `PythonConvertible` protocol
//===----------------------------------------------------------------------===//
public protocol PythonConvertible {
/// Creates a new instance from the given `PythonObject`, if possible.
/// - Note: Conversion may fail if the given `PythonObject` instance is
/// incompatible (e.g. a Python `string` object cannot be converted into an
/// `Int`).
init?(_ object: PythonObject)
/// A `PythonObject` instance representing this value.
var pythonObject: PythonObject { get }
}
public extension PythonObject {
/// Creates a new instance from a `PythonConvertible` value.
init<T : PythonConvertible>(_ object: T) {
self.init(object.pythonObject)
}
}
/// Internal helpers to convert `PythonConvertible` values to owned and borrowed
/// `PyObject` instances. These should not be made public.
fileprivate extension PythonConvertible {
var borrowedPyObject: UnsafeMutablePointer<PyObject> {
return pythonObject.borrowedPyObject
}
var ownedPyObject: OwnedPyObjectPointer {
return pythonObject.ownedPyObject
}
}
/// `PythonObject` is trivially `PythonConvertible`.
extension PythonObject : PythonConvertible {
public init(_ object: PythonObject) {
self.init(owning: object.ownedPyObject)
}
public var pythonObject: PythonObject { return self }
}
//===----------------------------------------------------------------------===//
// `PythonObject` callable implementation
//===----------------------------------------------------------------------===//
public extension PythonObject {
/// Returns a callable version of this `PythonObject`. When called, the result
/// throws a Swift error if the underlying Python function throws a Python
/// exception.
var throwing: ThrowingPythonObject {
return ThrowingPythonObject(self)
}
}
/// An error produced by a failable Python operation.
@_frozen
public enum PythonError : Error, Equatable {
/// A Python runtime exception, produced by calling a Python function.
case exception(PythonObject)
/// A failed call on a `PythonObject`.
/// Reasons for failure include:
/// - A non-callable Python object was called.
/// - An incorrect number of arguments were provided to the callable Python
/// object.
/// - An invalid keyword argument was specified.
case invalidCall(PythonObject)
/// A module import error.
case invalidModule(String)
}
extension PythonError : CustomStringConvertible {
public var description: String {
switch self {
case .exception(let p): return "Python exception: \(p)"
case .invalidCall(let p): return "Invalid Python call: \(p)"
case .invalidModule(let m): return "Invalid Python module: \(m)"
}
}
}
// Reflect a Python error (which must be active) into a Swift error if one is
// active.
private func throwPythonErrorIfPresent() throws {
if PyErr_Occurred() == nil { return }
var type: UnsafeMutablePointer<PyObject>?
var value: UnsafeMutablePointer<PyObject>?
var traceback: UnsafeMutablePointer<PyObject>?
// Fetch the exception and clear the exception state.
PyErr_Fetch(&type, &value, &traceback)
// The value for the exception may not be set but the type always should be.
let r = PythonObject(owning: value ?? type!)
throw PythonError.exception(r)
}
/// A `PythonObject` wrapper that enables throwing method calls.
/// Exceptions produced by Python functions are reflected as Swift errors and
/// thrown.
/// - Note: It is intentional that `ThrowingPythonObject` does not have the
/// `@dynamicCallable` attribute because the call syntax is unintuitive:
/// `x.throwing(arg1, arg2, ...)`. The methods will still be named
/// `dynamicallyCall` until further discussion/design.
@_fixed_layout
public struct ThrowingPythonObject {
private var base: PythonObject
fileprivate init(_ base: PythonObject) {
self.base = base
}
/// Call `self` with the specified positional arguments.
/// If the call fails for some reason, `PythonError.invalidCall` is thrown.
/// - Precondition: `self` must be a Python callable.
/// - Parameter args: Positional arguments for the Python callable.
@discardableResult
public func dynamicallyCall(
withArguments args: PythonConvertible...
) throws -> PythonObject {
return try dynamicallyCall(withArguments: args)
}
/// Call `self` with the specified positional arguments.
/// If the call fails for some reason, `PythonError.invalidCall` is thrown.
/// - Precondition: `self` must be a Python callable.
/// - Parameter args: Positional arguments for the Python callable.
@discardableResult
public func dynamicallyCall(
withArguments args: [PythonConvertible] = []
) throws -> PythonObject {
// Make sure there are no state errors.
if PyErr_Occurred() != nil {
// FIXME: This should be an assert, but the failure mode in Playgrounds
// is just awful.
fatalError("Python error state must be clear")
}
// Positional arguments are passed as a tuple of objects.
let argTuple = pyTuple(args.map { $0.pythonObject })
defer { Py_DecRef(argTuple) }
// Python calls always return a non-null object when successful. If the
// Python function produces the equivalent of C `void`, it returns the
// `None` object. A `null` result of `PyObjectCall` happens when there is an
// error, like `self` not being a Python callable.
let selfObject = base.ownedPyObject
defer { Py_DecRef(selfObject) }
guard let result = PyObject_CallObject(selfObject, argTuple) else {
// If a Python exception was thrown, throw a corresponding Swift error.
try throwPythonErrorIfPresent()
throw PythonError.invalidCall(base)
}
return PythonObject(owning: result)
}
/// Call `self` with the specified arguments.
/// If the call fails for some reason, `PythonError.invalidCall` is thrown.
/// - Precondition: `self` must be a Python callable.
/// - Parameter args: Positional or keyword arguments for the Python callable.
@discardableResult
public func dynamicallyCall(
withKeywordArguments args:
DictionaryLiteral<String, PythonConvertible> = [:]
) throws -> PythonObject {
// Make sure there are no state errors.
if PyErr_Occurred() != nil {
// FIXME: This should be an assert, but the failure mode in Playgrounds
// is just awful.
fatalError("Python error state must be clear")
}
// An array containing positional arguments.
var positionalArgs: [PythonObject] = []
// A dictionary object for storing keyword arguments, if any exist.
var kwdictObject: OwnedPyObjectPointer? = nil
for (key, value) in args {
if key.isEmpty {
positionalArgs.append(value.pythonObject)
continue
}
// Initialize dictionary object if necessary.
if kwdictObject == nil { kwdictObject = PyDict_New()! }
// Add key-value pair to the dictionary object.
// TODO: Handle duplicate keys.
// In Python, `SyntaxError: keyword argument repeated` is thrown.
let k = PythonObject(key).ownedPyObject
let v = value.ownedPyObject
PyDict_SetItem(kwdictObject, k, v)
Py_DecRef(k)
Py_DecRef(v)
}
defer { Py_DecRef(kwdictObject) } // Py_DecRef is `nil` safe.
// Positional arguments are passed as a tuple of objects.
let argTuple = pyTuple(positionalArgs)
defer { Py_DecRef(argTuple) }
// Python calls always return a non-null object when successful. If the
// Python function produces the equivalent of C `void`, it returns the
// `None` object. A `null` result of `PyObjectCall` happens when there is an
// error, like `self` not being a Python callable.
let selfObject = base.ownedPyObject
defer { Py_DecRef(selfObject) }
guard let result = PyObject_Call(selfObject, argTuple, kwdictObject) else {
// If a Python exception was thrown, throw a corresponding Swift error.
try throwPythonErrorIfPresent()
throw PythonError.invalidCall(base)
}
return PythonObject(owning: result)
}
/// Converts to a 2-tuple, if possible.
public var tuple2: (PythonObject, PythonObject)? {
let ct = base.checking
guard let elt0 = ct[0], let elt1 = ct[1] else {
return nil
}
return (elt0, elt1)
}
/// Converts to a 3-tuple, if possible.
public var tuple3: (PythonObject, PythonObject, PythonObject)? {
let ct = base.checking
guard let elt0 = ct[0], let elt1 = ct[1], let elt2 = ct[2] else {
return nil
}
return (elt0, elt1, elt2)
}
/// Converts to a 4-tuple, if possible.
public var tuple4: (PythonObject, PythonObject, PythonObject, PythonObject)? {
let ct = base.checking
guard let elt0 = ct[0], let elt1 = ct[1],
let elt2 = ct[2], let elt3 = ct[3] else {
return nil
}
return (elt0, elt1, elt2, elt3)
}
}
//===----------------------------------------------------------------------===//
// `PythonObject` member access implementation
//===----------------------------------------------------------------------===//
public extension PythonObject {
/// Returns a `PythonObject` wrapper capable of member accesses.
var checking: CheckingPythonObject {
return CheckingPythonObject(self)
}
}
/// A `PythonObject` wrapper that enables member accesses.
/// Member access operations return an `Optional` result. When member access
/// fails, `nil` is returned.
@dynamicMemberLookup
@_fixed_layout
public struct CheckingPythonObject {
/// The underlying `PythonObject`.
private var base: PythonObject
fileprivate init(_ base: PythonObject) {
self.base = base
}
public subscript(dynamicMember name: String) -> PythonObject? {
get {
let selfObject = base.ownedPyObject
defer { Py_DecRef(selfObject) }
guard let result = PyObject_GetAttrString(selfObject, name) else {
PyErr_Clear()
return nil
}
// `PyObject_GetAttrString` returns +1 result.
return PythonObject(owning: result)
}
}
/// Access the element corresponding to the specified `PythonConvertible`
/// values representing a key.
/// - Note: This is equivalent to `object[key]` in Python.
public subscript(key: [PythonConvertible]) -> PythonObject? {
get {
let keyObject = flattenedSubscriptIndices(key)
let selfObject = base.ownedPyObject
defer {
Py_DecRef(keyObject)
Py_DecRef(selfObject)
}
// `PyObject_GetItem` returns +1 reference.
if let result = PyObject_GetItem(selfObject, keyObject) {
return PythonObject(owning: result)
}
PyErr_Clear()
return nil
}
nonmutating set {
let keyObject = flattenedSubscriptIndices(key)
let selfObject = base.ownedPyObject
defer {
Py_DecRef(keyObject)
Py_DecRef(selfObject)
}
if let newValue = newValue {
let newValueObject = newValue.ownedPyObject
PyObject_SetItem(selfObject, keyObject, newValueObject)
Py_DecRef(newValueObject)
} else {
// Assigning `nil` deletes the key, just like Swift dictionaries.
PyObject_DelItem(selfObject, keyObject)
}
}
}
/// Access the element corresponding to the specified `PythonConvertible`
/// values representing a key.
/// - Note: This is equivalent to `object[key]` in Python.
public subscript(key: PythonConvertible...) -> PythonObject? {
get {
return self[key]
}
nonmutating set {
self[key] = newValue
}
}
/// Converts to a 2-tuple, if possible.
public var tuple2: (PythonObject, PythonObject)? {
guard let elt0 = self[0], let elt1 = self[1] else {
return nil
}
return (elt0, elt1)
}
/// Converts to a 3-tuple, if possible.
public var tuple3: (PythonObject, PythonObject, PythonObject)? {
guard let elt0 = self[0], let elt1 = self[1], let elt2 = self[2] else {
return nil
}
return (elt0, elt1, elt2)
}
/// Converts to a 4-tuple, if possible.
public var tuple4: (PythonObject, PythonObject, PythonObject, PythonObject)? {
guard let elt0 = self[0], let elt1 = self[1],
let elt2 = self[2], let elt3 = self[3] else {
return nil
}
return (elt0, elt1, elt2, elt3)
}
}
//===----------------------------------------------------------------------===//
// Core `PythonObject` API
//===----------------------------------------------------------------------===//
/// Converts an array of indices into a `PythonObject` representing a flattened
/// index.
private func flattenedSubscriptIndices(
_ indices: [PythonConvertible]
) -> OwnedPyObjectPointer {
if indices.count == 1 {
return indices[0].ownedPyObject
}
return pyTuple(indices.map { $0.pythonObject })
}
public extension PythonObject {
subscript(dynamicMember memberName: String) -> PythonObject {
get {
guard let member = checking[dynamicMember: memberName] else {
fatalError("Could not access PythonObject member '\(memberName)'")
}
return member
}
nonmutating set {
let selfObject = ownedPyObject
defer { Py_DecRef(selfObject) }
let valueObject = newValue.ownedPyObject
defer { Py_DecRef(valueObject) }
if PyObject_SetAttrString(selfObject, memberName, valueObject) == -1 {
try! throwPythonErrorIfPresent()
fatalError("""
Could not set PythonObject member '\(memberName)' to the specified \
value
""")
}
}
}
/// Access the element corresponding to the specified `PythonConvertible`
/// values representing a key.
/// - Note: This is equivalent to `object[key]` in Python.
subscript(key: PythonConvertible...) -> PythonObject {
get {
guard let item = checking[key] else {
fatalError("""
Could not access PythonObject element corresponding to the specified \
key values
""")
}
return item
}
nonmutating set {
checking[key] = newValue
}
}
/// Converts to a 2-tuple.
var tuple2: (PythonObject, PythonObject) {
guard let result = checking.tuple2 else {
fatalError("Could not convert PythonObject to a 2-element tuple")
}
return result
}
/// Converts to a 3-tuple.
var tuple3: (PythonObject, PythonObject, PythonObject) {
guard let result = checking.tuple3 else {
fatalError("Could not convert PythonObject to a 3-element tuple")
}
return result
}
/// Converts to a 4-tuple.
var tuple4: (PythonObject, PythonObject, PythonObject, PythonObject) {
guard let result = checking.tuple4 else {
fatalError("Could not convert PythonObject to a 4-element tuple")
}
return result
}
/// Call `self` with the specified positional arguments.
/// - Precondition: `self` must be a Python callable.
/// - Parameter args: Positional arguments for the Python callable.
@discardableResult
func dynamicallyCall(
withArguments args: [PythonConvertible] = []
) -> PythonObject {
return try! throwing.dynamicallyCall(withArguments: args)
}
/// Call `self` with the specified arguments.
/// - Precondition: `self` must be a Python callable.
/// - Parameter args: Positional or keyword arguments for the Python callable.
@discardableResult
func dynamicallyCall(
withKeywordArguments args:
DictionaryLiteral<String, PythonConvertible> = [:]
) -> PythonObject {
return try! throwing.dynamicallyCall(withKeywordArguments: args)
}
}
//===----------------------------------------------------------------------===//
// Python interface implementation
//===----------------------------------------------------------------------===//
/// The global Python interface.
///
/// You can import Python modules and access Python builtin types and functions
/// via the `Python` global variable.
///
/// import Python
/// // Import modules.
/// let os = Python.import("os")
/// let np = Python.import("numpy")
///
/// // Use builtin types and functions.
/// let list: PythonObject = [1, 2, 3]
/// print(Python.len(list)) // Prints 3.
/// print(Python.type(list) == Python.list) // Prints true.
@_fixed_layout
public let Python = PythonInterface()
/// An interface for Python.
///
/// `PythonInterface` allows interaction with Python. It can be used to import
/// modules and dynamically access Python builtin types and functions.
/// - Note: It is not intended for `PythonInterface` to be initialized
/// directly. Instead, please use the global instance of `PythonInterface`
/// called `Python`.
@_fixed_layout
@dynamicMemberLookup
public struct PythonInterface {
/// A dictionary of the Python builtins.
public let builtins: PythonObject
init() {
Py_Initialize() // Initialize Python
builtins = PythonObject(borrowing: PyEval_GetBuiltins())
}
public func attemptImport(_ name: String) throws -> PythonObject {
guard let module = PyImport_ImportModule(name) else {
try throwPythonErrorIfPresent()
throw PythonError.invalidModule(name)
}
return PythonObject(owning: module)
}
public func `import`(_ name: String) -> PythonObject {
return try! attemptImport(name)
}
public func updatePath(to path: String) {
var cStr = path.utf8CString
cStr.withUnsafeMutableBufferPointer { buffPtr in
PySys_SetPath(buffPtr.baseAddress)
}
}
public subscript(dynamicMember name: String) -> PythonObject {
return builtins[name]
}
}
//===----------------------------------------------------------------------===//
// Helpers for Python slice and tuple types
//===----------------------------------------------------------------------===//
private func pySlice(_ start: PythonConvertible?,
_ stop: PythonConvertible?,
_ step: PythonConvertible? = nil) -> OwnedPyObjectPointer {
let startP = start?.ownedPyObject
let stopP = stop?.ownedPyObject
let stepP = step?.ownedPyObject
// `PySlice_New` takes each operand at +0, and returns +1.
let result = PySlice_New(startP, stopP, stepP)!
Py_DecRef(startP)
Py_DecRef(stopP)
Py_DecRef(stepP) // `Py_DecRef` is `nil` safe.
return result
}
// Create a Python tuple object with the specified elements.
private func pyTuple<T : Collection>(_ vals: T) -> OwnedPyObjectPointer
where T.Element : PythonConvertible {
let tuple = PyTuple_New(vals.count)!
for (index, element) in vals.enumerated() {
// `PyTuple_SetItem` steals the reference of the object stored.
PyTuple_SetItem(tuple, index, element.ownedPyObject)
}
return tuple
}
public extension PythonObject {
// FIXME: This should be subsumed by Swift ranges and strides. Python has a
// very extravagant model though, it isn't clear how best to represent this
// in Swift.
//
// Initial thoughts are that we should sugar the obvious cases (so you can
// use 0...100 in a subscript) but then provide this method for the fully
// general case.
//
// We also need conditional conformances to allow range if PythonObject is to
// be a Slice. We can probably get away with a bunch of overloads for now
// given that slices are typically used with concrete operands.
init(sliceStart start: PythonConvertible?,
stop: PythonConvertible?,
step: PythonConvertible? = nil) {
self.init(owning: pySlice(start, stop, step))
}
// Tuples require explicit support because tuple types cannot conform to
// protocols.
init(tupleOf elements: PythonConvertible...) {
self.init(tupleContentsOf: elements)
}
init<T : Collection>(tupleContentsOf elements: T)
where T.Element == PythonConvertible {
self.init(owning: pyTuple(elements.map { $0.pythonObject }))
}
init<T : Collection>(tupleContentsOf elements: T)
where T.Element : PythonConvertible {
self.init(owning: pyTuple(elements))
}
}
//===----------------------------------------------------------------------===//
// `PythonConvertible` conformance for basic Swift types
//===----------------------------------------------------------------------===//
/// Return true if the specified objects an instance of the low-level Python
/// type descriptor passed in as 'type'.
private func isType(_ object: PythonObject,
type: UnsafeMutableRawPointer) -> Bool {
let typePyRef = PythonObject(
borrowing: type.assumingMemoryBound(to: PyObject.self)
)
let result = Python.isinstance(object, typePyRef)
// We cannot use the normal failable Bool initializer from `PythonObject`
// here because would cause an infinite loop.
let pyObject = result.ownedPyObject
defer { Py_DecRef(pyObject) }
// Anything not equal to `Py_ZeroStruct` is truthy.
return !(pyObject == &_Py_ZeroStruct)
}
private func == (_ x: UnsafeMutablePointer<PyObject>,
_ y: UnsafeMutableRawPointer) -> Bool {
return x == y.assumingMemoryBound(to: PyObject.self)
}
extension Bool : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard isType(pythonObject, type: &PyBool_Type) else { return nil }
let pyObject = pythonObject.ownedPyObject
defer { Py_DecRef(pyObject) }
self = pyObject == &_Py_TrueStruct
}
public var pythonObject: PythonObject {
_ = Python // Ensure Python is initialized.
return PythonObject(owning: PyBool_FromLong(self ? 1 : 0))
}
}
extension String : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
let pyObject = pythonObject.ownedPyObject
defer { Py_DecRef(pyObject) }
guard let cString = PyString_AsString(pyObject) else {
PyErr_Clear()
return nil
}
self.init(cString: cString)
}
public var pythonObject: PythonObject {
_ = Python // Ensure Python is initialized.
let v = utf8CString.withUnsafeBufferPointer {
// 1 is subtracted from the C string length to trim the trailing null
// character (`\0`).
PyString_FromStringAndSize($0.baseAddress, $0.count - 1)!
}
return PythonObject(owning: v)
}
}
fileprivate extension PythonObject {
// Converts a `PythonObject` to the given type by applying the appropriate
// converter function and checking the error value.
func converted<T : Equatable>(
withError errorValue: T, by converter: (OwnedPyObjectPointer) -> T
) -> T? {
let pyObject = ownedPyObject
defer { Py_DecRef(pyObject) }
assert(PyErr_Occurred() == nil,
"Python error occurred somewhere but wasn't handled")
let value = converter(pyObject)
guard value != errorValue || PyErr_Occurred() == nil else {
PyErr_Clear()
return nil
}
return value
}
}
extension Int : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
// `PyInt_AsLong` return -1 and sets an error if the Python object is not
// integer compatible.
guard let value = pythonObject.converted(withError: -1,
by: PyInt_AsLong) else {
return nil
}
self = value
}
public var pythonObject: PythonObject {
_ = Python // Ensure Python is initialized.
return PythonObject(owning: PyInt_FromLong(self))
}
}
extension UInt : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
// `PyInt_AsUnsignedLongMask` isn't documented as such, but in fact it does
// return -1 and set an error if the Python object is not integer
// compatible.
guard let value = pythonObject.converted(
withError: ~0, by: PyInt_AsUnsignedLongMask) else {
return nil
}
self = value
}
public var pythonObject: PythonObject {
_ = Python // Ensure Python is initialized.
return PythonObject(owning: PyInt_FromSize_t(Int(self)))
}
}
extension Double : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
// `PyFloat_AsDouble` return -1 and sets an error if the Python object is
// not float compatible.
guard let value = pythonObject.converted(withError: -1,
by: PyFloat_AsDouble) else {
return nil
}
self = value
}
public var pythonObject: PythonObject {
_ = Python // Ensure Python is initialized.
return PythonObject(owning: PyFloat_FromDouble(self))
}
}
//===----------------------------------------------------------------------===//
// `PythonConvertible` conformances for `FixedWidthInteger` and `Float`
//===----------------------------------------------------------------------===//
/// Any `FixedWidthInteger` type is `PythonConvertible` via the `Int`/`UInt`
/// implementation.
extension Int8 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = Int(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return Int(self).pythonObject
}
}
extension Int16 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = Int(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return Int(self).pythonObject
}
}
extension Int32 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = Int(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return Int(self).pythonObject
}
}
extension Int64 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = Int(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return Int(self).pythonObject
}
}
extension UInt8 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = UInt(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return UInt(self).pythonObject
}
}
extension UInt16 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = UInt(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return UInt(self).pythonObject
}
}
extension UInt32 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = UInt(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return UInt(self).pythonObject
}
}
extension UInt64 : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let i = UInt(pythonObject) else { return nil }
self.init(i)
}
public var pythonObject: PythonObject {
return UInt(self).pythonObject
}
}
/// `Float` is `PythonConvertible` via the `Double` implementation.
extension Float : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
guard let v = Double(pythonObject) else { return nil }
self.init(v)
}
public var pythonObject: PythonObject {
return Double(self).pythonObject
}
}
//===----------------------------------------------------------------------===//
// `PythonConvertible` conformance for `Array` and `Dictionary`
//===----------------------------------------------------------------------===//
// `Array` conditionally conforms to `PythonConvertible` if the `Element`
// associated type does.
extension Array : PythonConvertible where Element : PythonConvertible {
public init?(_ pythonObject: PythonObject) {
self = []
for elementObject in pythonObject {
guard let element = Element(elementObject) else { return nil }
append(element)
}
}