-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPython.swift
More file actions
548 lines (455 loc) · 18.2 KB
/
Copy pathPython.swift
File metadata and controls
548 lines (455 loc) · 18.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
import Foundation
@_exported import PythonWrapper
public typealias PyObjectRef = UnsafeMutablePointer<PyObject>
public let PyFalse = UnsafeMutableRawPointer( &_Py_FalseStruct ).assumingMemoryBound(to: PyObject.self)
public let PyTrue = UnsafeMutableRawPointer( &_Py_TrueStruct ).assumingMemoryBound(to: PyObject.self)
public let PyNone = UnsafeMutableRawPointer( &_Py_NoneStruct ).assumingMemoryBound(to: PyObject.self)
public var stdout : StdoutCapture!
public var swiftModule : SwiftModule!
public var Python = PythonInterface()
fileprivate func throwErrorIfPresent() throws {
if PyErr_Occurred() == nil { return }
var type: PyObjectRef?
var value: PyObjectRef?
var traceback: PyObjectRef?
// 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 resultObject = PythonObject(consuming: value ?? type!)
let tracebackObject = traceback.flatMap { PythonObject(consuming: $0) }
PyErr_Print()
PyErr_Clear()
throw PythonError.exception(resultObject, traceback: tracebackObject)
}
@dynamicMemberLookup
public class PythonInterface {
public var pyBuiltins: PythonObject! // this is the Python builtins object
public var pyGlobals: PyObjectRef!
public var builtins : [ String : PythonObject ] = [:] // this is a Swift dictionary mapping names to Python builtin objects
public init() {
// This is the appropriate value for running the app under xcode
var hh = Bundle.main.privateFrameworksURL!
let env = ProcessInfo.processInfo.environment
if let _ = env["PLAYGROUND_COMMUNICATION_SOCKET"],
let bb = env["PACKAGE_RESOURCE_BUNDLE_PATH"] {
hh = URL(string: bb)!
}
let hh1 = hh.appendingPathComponent("Python.framework").appendingPathComponent("Versions").appendingPathComponent("Current")
// print("setting PythonHomw: \(hh1.path)")
// FIXME: Py_SetPythonHome is deprecated -- so need to find the modern way to do this
hh1.path.withWideChars {
Py_SetPythonHome( $0 )
}
setup()
start0()
}
public func setup() {
stdout = StdoutCapture()
swiftModule = SwiftModule()
Py_Initialize() // Initialize Python
}
public func start0() {
// =======================================================================
// below is the actual initialization of the Python interpreter
// Py_Initialize() // Initialize Python
let __main__ = PyImport_ImportModule("__main__")
pyGlobals = PyModule_GetDict( __main__ )
pyGlobals.pointee.ob_refcnt += 1
let stdcn = "stdout_capture"
let stdcnn = stdcn.cString(using: .utf8)
let stdc = PyImport_ImportModule(stdcnn)
try! throwErrorIfPresent()
PyDict_SetItem(pyGlobals, stdcn.pythonObject.retained(), stdc)
}
public func start() {
let smn = "swift_module"
let smnn = smn.cString(using: .utf8)!
let sm = PyImport_ImportModule(smnn)
try! throwErrorIfPresent()
PyDict_SetItem(pyGlobals, smn.pythonObject.retained(), sm)
pyBuiltins = PythonObject(retaining: PyEval_GetBuiltins())
// FIXME: this should be in the app! not in the package!!!
let sys = self.sys
let bb = Bundle.main.resourceURL!
let bb1 = bb.appendingPathComponent("venv")
try! sys.path.insert(0, bb1.path)
let bb2 = bb1.appendingPathComponent("site-packages")
try! sys.path.insert(1, bb2.path)
do {
let _ = try Python.run("""
import ssl
import certifi
def _create_certifi_context():
return ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH, cafile=certifi.where())
ssl._create_default_https_context = _create_certifi_context
""")
} catch(let e) {
print(e)
}
}
public subscript(dynamicMember name: String) -> PythonObject {
get {
if let obj = builtins[name] {
return obj
}
if let obj = pyBuiltins[name] {
return obj
}
if let module = PyImport_ImportModule(name) {
let res = PythonObject(consuming: module)
builtins[name] = res
return res
}
try! throwErrorIfPresent()
return PythonObject(consuming: PyNone)
}
}
public func imports( _ sub : String, from: String) -> PythonObject {
let a = PyList_New(1)
let z = PyList_SetItem(a, 0, sub.pythonObject.pointer)
let iml = PyImport_ImportModuleLevel(from, nil, nil, a, 0)
return PythonObject(retaining: iml!)
}
// Python error (if active) thrown as a Swift error
public subscript<T>(dynamicMember name: String) -> T? where T : ConvertibleToPython {
get {
if let obj = builtins[name] {
return obj as? T
}
if let obj = pyBuiltins[name] {
return obj as? T
}
if let module = PyImport_ImportModule(name) {
let res = PythonObject(consuming: module)
builtins[name] = res
return res as? T
}
try! throwErrorIfPresent()
return PythonObject(consuming: PyNone) as? T
}
set {
PyDict_SetItem(pyGlobals, name.pythonObject.retained(), newValue.pythonObject.retained())
}
}
public func run(_ str : String, returning: String) throws -> PythonObject? {
return try self.run(str, returning: [returning]).first!
}
public func run(_ str : String, returning: [String] = []) throws -> [PythonObject?] {
// If I had an error somewhere and forgot to check, now is when I'm going to ignore it.
PyErr_Clear()
PyRun_SimpleStringFlags(str, nil)
try throwErrorIfPresent()
let r = returning.map {
// PyDict_GetItemString(pyGlobals, $0.??)
let z = $0.pythonObject
if let kk = PyDict_GetItem(pyGlobals, z.pointer) {
return PythonObject(retaining: kk)
} else {
return PythonObject(retaining: PyNone)
}
}
return r
}
public func eval(_ str: String) throws -> PythonObject {
PyErr_Clear()
let kk = PyDict_New()
let j = PyRun_StringFlags(str, Py_eval_input, pyGlobals, kk, nil)
try throwErrorIfPresent()
let r = PythonObject(retaining: j!)
return r
}
}
@dynamicCallable
@dynamicMemberLookup
public struct PythonObject {
var pointer: PyObjectRef
public init(retaining pointer: PyObjectRef) {
self.pointer = pointer
retain()
}
public init(consuming pointer: PyObjectRef) {
self.pointer = pointer
}
public func retain() {
Py_IncRef(pointer)
}
public func retained() -> PyObjectRef {
retain()
return pointer
}
public func release() {
Py_DecRef(pointer)
}
}
extension PythonObject : CustomStringConvertible {
public var description: String {
if Py_IsNone(pointer) != 0 {
return "None"
} else {
let z = PythonObject(retaining: PyEval_GetBuiltins())
let str = z["str"]!
return try! String( str(self))!
}
}
public var debugDescription: String {
return description
}
}
extension PythonObject : CustomPlaygroundDisplayConvertible {
public var playgroundDescription: Any {
return description
}
}
extension PythonObject : CustomReflectable {
public var customMirror: Mirror {
return Mirror(self, children: [], displayStyle: .struct)
}
}
public extension PythonObject {
init(tupleOf elements: ConvertibleToPython...) {
self.init(tupleContentsOf: elements)
}
init<T : Collection>(tupleContentsOf elements: T) where T.Element == ConvertibleToPython {
let tuple = PyTuple_New(elements.count)!
for (index, element) in elements.enumerated() {
PyTuple_SetItem(tuple, index, element.pythonObject.retained())
}
self.init(consuming: tuple)
}
}
public extension PythonObject {
subscript(dynamicMember memberName: String) -> PythonObject {
get {
if let result = (memberName.utf8CString.withUnsafeBufferPointer {
PyObject_GetAttrString(pointer, $0.baseAddress) }) {
return PythonObject(consuming: result)
}
if self.isType(&PyModule_Type) {
let s = String(self.__name__)!+"."+memberName
return PythonObject(consuming: PyImport_Import(PythonObject(s).retained()))
}
try! throwErrorIfPresent()
return PythonObject(retaining: PyNone)
}
nonmutating set {
let selfObject = retained()
defer { release() }
let valueObject = newValue.retained()
defer { newValue.release() }
if PyObject_SetAttrString(selfObject, memberName, valueObject) == -1 {
try! throwErrorIfPresent()
fatalError("Could not set PythonObject member '\(memberName)' to the specified value")
}
}
}
subscript(key: ConvertibleToPython) -> PythonObject? {
get {
guard let result = PyObject_GetItem(pointer, key.pythonObject.pointer) else { return nil }
return PythonObject(retaining: result)
}
nonmutating set {
if let newValue = newValue {
PyObject_SetItem(pointer, key.pythonObject.pointer, newValue.pythonObject.pointer)
} else {
PyObject_DelItem(pointer, key.pythonObject.pointer)
}
try! throwErrorIfPresent()
}
}
/// 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
func dynamicallyCall(
withArguments args: [ConvertibleToPython] = []
) throws -> PythonObject {
try throwErrorIfPresent()
// Positional arguments are passed as a tuple of objects.
let argTuple = PythonObject(tupleContentsOf: args)
defer { argTuple.release() }
// 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 = retained()
defer { release() }
guard let result = PyObject_CallObject(selfObject, argTuple.pointer) else {
// If a Python exception was thrown, throw a corresponding Swift error.
try throwErrorIfPresent()
throw PythonError.invalidCall(self)
}
return PythonObject(consuming: 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
func dynamicallyCall(
withKeywordArguments args:
KeyValuePairs<String, ConvertibleToPython> = [:]
) throws -> PythonObject {
try throwErrorIfPresent()
// An array containing positional arguments.
var positionalArgs: [PythonObject] = []
// A dictionary object for storing keyword arguments, if any exist.
var kwdictObject: PyObjectRef? = 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).retained()
let v = value.pythonObject.retained()
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 = PythonObject(tupleContentsOf: positionalArgs)
defer { argTuple.release() }
// 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 = retained()
defer { release() }
guard let result = PyObject_Call(selfObject, argTuple.pointer, kwdictObject) else {
// If a Python exception was thrown, throw a corresponding Swift error.
try throwErrorIfPresent()
throw PythonError.invalidCall(self)
}
return PythonObject(consuming: result)
}
}
//=======================================================================
// String extensions
//=======================================================================
extension String {
/// Calls the given closure with a pointer to the contents of the string represented as a null-terminated wchar_t array.
func withWideChars<Result>(_ body: (UnsafeMutablePointer<wchar_t>) -> Result) -> Result {
var u32 = self.unicodeScalars.map { wchar_t(bitPattern: $0.value) } + [0]
return u32.withUnsafeMutableBufferPointer { body($0.baseAddress!) }
}
}
//================================================================================
public enum PythonError : Error, Equatable {
case exception(PythonObject, traceback: PythonObject?)
case invalidCall(PythonObject)
case invalidModule(String)
case indexError(PythonObject)
case runError(PythonObject)
}
extension PythonError : CustomStringConvertible {
public var description: String {
switch self {
case .exception(let e, let t):
var exceptionDescription = "Python exception: \(e)"
if let t = t {
exceptionDescription += try! "\nTraceback: \(PythonObject("").join(Python.traceback.format_tb(t)))"
}
return exceptionDescription
case .invalidCall(let e): return "Invalid Python call: \(e)"
case .invalidModule(let m): return "Invalid Python module: \(m)"
case .indexError(let m): return "Index error: \(m)"
case .runError(let m): return "Run error: \(m)"
}
}
}
//================================================================================
//==============================================
// Standard operators
//==============================================
private typealias PythonBinaryOp = (PyObjectRef?, PyObjectRef?) -> PyObjectRef?
public extension PythonObject {
private static func binaryOp(_ op: PythonBinaryOp, lhs: PythonObject, rhs: PythonObject) -> PythonObject {
let result = op(lhs.pointer, rhs.pointer)
try! throwErrorIfPresent()
return PythonObject(consuming: result!)
}
static func + (lhs: PythonObject, rhs: PythonObject) -> PythonObject { return binaryOp(PyNumber_Add, lhs: lhs, rhs: rhs) }
static func - (lhs: PythonObject, rhs: PythonObject) -> PythonObject { return binaryOp(PyNumber_Subtract, lhs: lhs, rhs: rhs) }
static func * (lhs: PythonObject, rhs: PythonObject) -> PythonObject { return binaryOp(PyNumber_Multiply, lhs: lhs, rhs: rhs) }
static func / (lhs: PythonObject, rhs: PythonObject) -> PythonObject { return binaryOp(PyNumber_TrueDivide, lhs: lhs, rhs: rhs) }
static func += (lhs: inout PythonObject, rhs: PythonObject) { lhs = binaryOp(PyNumber_InPlaceAdd, lhs: lhs, rhs: rhs) }
static func -= (lhs: inout PythonObject, rhs: PythonObject) { lhs = binaryOp(PyNumber_InPlaceSubtract, lhs: lhs, rhs: rhs) }
static func *= (lhs: inout PythonObject, rhs: PythonObject) { lhs = binaryOp(PyNumber_InPlaceMultiply, lhs: lhs, rhs: rhs) }
static func /= (lhs: inout PythonObject, rhs: PythonObject) { lhs = binaryOp(PyNumber_InPlaceTrueDivide, lhs: lhs, rhs: rhs) }
}
//===========================================================
// Python Comparable and Equatable
//===========================================================
extension PythonObject : Equatable, Comparable {
private func compared(to other: PythonObject, byOp: Int32) -> Bool {
retain(); other.retain(); defer { release(); other.release() }
switch PyObject_RichCompareBool(pointer, other.pointer, byOp) {
case 0: return false
case 1: return true
default:
try! throwErrorIfPresent()
fatalError("No result or error returned when comparing \(self) to \(other)")
}
}
public static func == (lhs: PythonObject, rhs: PythonObject) -> Bool { return lhs.compared(to: rhs, byOp: Py_EQ) }
public static func != (lhs: PythonObject, rhs: PythonObject) -> Bool { return lhs.compared(to: rhs, byOp: Py_NE) }
public static func < (lhs: PythonObject, rhs: PythonObject) -> Bool { return lhs.compared(to: rhs, byOp: Py_LT) }
public static func <= (lhs: PythonObject, rhs: PythonObject) -> Bool { return lhs.compared(to: rhs, byOp: Py_LE) }
public static func > (lhs: PythonObject, rhs: PythonObject) -> Bool { return lhs.compared(to: rhs, byOp: Py_GT) }
public static func >= (lhs: PythonObject, rhs: PythonObject) -> Bool { return lhs.compared(to: rhs, byOp: Py_GE) }
}
//======================================================================
extension PythonObject : Hashable {
public func hash(into hasher: inout Hasher) {
guard let hash = try? Int(self.__hash__()) else {
fatalError("Cannot use '__hash__' on \(self)")
}
hasher.combine(hash)
}
}
extension PythonObject : MutableCollection {
public typealias Index = PythonObject
public typealias Element = PythonObject
public var startIndex: Index { return PythonObject(0) }
public var endIndex: Index { return try! Python.len(self) }
public func index(after i: Index) -> Index { return i + PythonObject(1) }
public subscript(index: PythonObject) -> PythonObject {
get {
if let j = self[index as ConvertibleToPython] { return j }
try! throwErrorIfPresent()
return PythonObject(consuming: PyExc_IndexError)
}
set {
self[index as ConvertibleToPython] = newValue
}
}
}
//=======================================================
// Python Iterator (Sequence)
//=======================================================
extension PythonObject : Sequence {
public struct Iterator : IteratorProtocol {
fileprivate let pythonIterator: PythonObject
public func next() -> PythonObject? {
guard let result = PyIter_Next(self.pythonIterator.pointer) else {
PyErr_Print() // try! throwErrorIfPresent()
PyErr_Clear()
return nil
}
return PythonObject(consuming: result)
}
}
public func makeIterator() -> Iterator {
guard let result = PyObject_GetIter(pointer) else {
try! throwErrorIfPresent()
preconditionFailure()
}
return Iterator(pythonIterator: PythonObject(consuming: result))
}
}