forked from gotray/go-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
object.go
497 lines (442 loc) · 10.6 KB
/
object.go
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
package gp
/*
#include <Python.h>
*/
import "C"
import (
"fmt"
"reflect"
"runtime"
"unsafe"
)
// pyObject is a wrapper type that holds a Python Object and automatically calls
// the Python Object's DecRef method during garbage collection.
type pyObject struct {
obj *C.PyObject
}
func (obj *pyObject) Obj() *PyObject {
if obj == nil {
return nil
}
return obj.obj
}
func (obj *pyObject) Nil() bool {
return obj == nil
}
func (obj *pyObject) Ensure() {
if obj == nil {
C.PyErr_Print()
panic("nil Python object")
}
}
// ----------------------------------------------------------------------------
type Object struct {
*pyObject
}
func FromPy(obj *PyObject) Object {
return newObject(obj)
}
func (obj Object) object() Object {
return obj
}
func newObject(obj *PyObject) Object {
if obj == nil {
C.PyErr_Print()
return Object{}
}
o := &pyObject{obj: obj}
p := Object{o}
runtime.SetFinalizer(o, func(o *pyObject) {
C.Py_DecRef(o.obj)
})
return p
}
func (obj Object) Dir() List {
return obj.Call("__dir__").AsList()
}
func (obj Object) Attr(name string) Object {
cname := AllocCStr(name)
o := C.PyObject_GetAttrString(obj.obj, cname)
C.free(unsafe.Pointer(cname))
return newObject(o)
}
func (obj Object) AttrFloat(name string) Float {
return obj.Attr(name).AsFloat()
}
func (obj Object) AttrLong(name string) Long {
return obj.Attr(name).AsLong()
}
func (obj Object) AttrString(name string) Str {
return obj.Attr(name).AsStr()
}
func (obj Object) AttrBytes(name string) Bytes {
return obj.Attr(name).AsBytes()
}
func (obj Object) AttrBool(name string) Bool {
return obj.Attr(name).AsBool()
}
func (obj Object) AttrDict(name string) Dict {
return obj.Attr(name).AsDict()
}
func (obj Object) AttrList(name string) List {
return obj.Attr(name).AsList()
}
func (obj Object) AttrTuple(name string) Tuple {
return obj.Attr(name).AsTuple()
}
func (obj Object) AttrFunc(name string) Func {
return obj.Attr(name).AsFunc()
}
func (obj Object) SetAttr(name string, value any) {
cname := AllocCStr(name)
C.PyObject_SetAttrString(obj.obj, cname, From(value).obj)
C.free(unsafe.Pointer(cname))
}
func (obj Object) IsLong() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyLong_Type) != 0
}
func (obj Object) IsFloat() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyFloat_Type) != 0
}
func (obj Object) IsComplex() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyComplex_Type) != 0
}
func (obj Object) IsStr() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyUnicode_Type) != 0
}
func (obj Object) IsBytes() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyBytes_Type) != 0
}
func (obj Object) IsBool() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyBool_Type) != 0
}
func (obj Object) IsList() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyList_Type) != 0
}
func (obj Object) IsTuple() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyTuple_Type) != 0
}
func (obj Object) IsDict() bool {
return C.Py_IS_TYPE(obj.obj, &C.PyDict_Type) != 0
}
func (obj Object) AsFloat() Float {
return Cast[Float](obj)
}
func (obj Object) AsLong() Long {
return Cast[Long](obj)
}
func (obj Object) AsComplex() Complex {
return Cast[Complex](obj)
}
func (obj Object) AsStr() Str {
return Cast[Str](obj)
}
func (obj Object) AsBytes() Bytes {
return Cast[Bytes](obj)
}
func (obj Object) AsBool() Bool {
return Cast[Bool](obj)
}
func (obj Object) AsDict() Dict {
return Cast[Dict](obj)
}
func (obj Object) AsList() List {
return Cast[List](obj)
}
func (obj Object) AsTuple() Tuple {
return Cast[Tuple](obj)
}
func (obj Object) AsFunc() Func {
return Cast[Func](obj)
}
func (obj Object) AsModule() Module {
return Cast[Module](obj)
}
func (obj Object) Call(name string, args ...any) Object {
fn := Cast[Func](obj.Attr(name))
argsTuple, kwArgs := splitArgs(args...)
if kwArgs == nil {
return fn.CallObject(argsTuple)
} else {
return fn.CallObjectKw(argsTuple, kwArgs)
}
}
func (obj Object) Repr() string {
return newStr(C.PyObject_Repr(obj.obj)).String()
}
func (obj Object) Type() Object {
return obj.Attr("__class__")
}
func (obj Object) String() string {
return newStr(C.PyObject_Str(obj.obj)).String()
}
func (obj Object) Obj() *PyObject {
if obj.Nil() {
return nil
}
return obj.pyObject.obj
}
func From(v any) Object {
switch v := v.(type) {
case Objecter:
return newObject(v.Obj())
case int8:
return newObject(C.PyLong_FromLong(C.long(v)))
case int16:
return newObject(C.PyLong_FromLong(C.long(v)))
case int32:
return newObject(C.PyLong_FromLong(C.long(v)))
case int64:
return newObject(C.PyLong_FromLongLong(C.longlong(v)))
case int:
return newObject(C.PyLong_FromLong(C.long(v)))
case uint8:
return newObject(C.PyLong_FromLong(C.long(v)))
case uint16:
return newObject(C.PyLong_FromLong(C.long(v)))
case uint32:
return newObject(C.PyLong_FromLong(C.long(v)))
case uint64:
return newObject(C.PyLong_FromUnsignedLongLong(C.ulonglong(v)))
case uint:
return newObject(C.PyLong_FromUnsignedLong(C.ulong(v)))
case float64:
return newObject(C.PyFloat_FromDouble(C.double(v)))
case string:
cstr := AllocCStr(v)
o := C.PyUnicode_FromString(cstr)
C.free(unsafe.Pointer(cstr))
return newObject(o)
case complex128:
return MakeComplex(v).Object
case complex64:
return MakeComplex(complex128(v)).Object
case []byte:
return MakeBytes(v).Object
case bool:
if v {
return True().Object
} else {
return False().Object
}
case *C.PyObject:
return newObject(v)
default:
vv := reflect.ValueOf(v)
switch vv.Kind() {
case reflect.Slice:
return fromSlice(vv).Object
case reflect.Map:
return fromMap(vv).Object
case reflect.Struct:
return fromStruct(vv)
}
panic(fmt.Errorf("unsupported type for Python: %T\n", v))
}
}
func ToValue(obj Object, v reflect.Value) bool {
// Handle nil pointer
if !v.IsValid() || !v.CanSet() {
return false
}
switch v.Kind() {
case reflect.Int8:
fallthrough
case reflect.Int16:
fallthrough
case reflect.Int32:
fallthrough
case reflect.Int64:
fallthrough
case reflect.Int:
if obj.IsLong() {
v.SetInt(Cast[Long](obj).Int64())
} else {
return false
}
case reflect.Uint8:
fallthrough
case reflect.Uint16:
fallthrough
case reflect.Uint32:
fallthrough
case reflect.Uint64:
fallthrough
case reflect.Uint:
if obj.IsLong() {
v.SetUint(Cast[Long](obj).Uint64())
} else {
return false
}
case reflect.Float32:
fallthrough
case reflect.Float64:
if obj.IsFloat() || obj.IsLong() {
v.SetFloat(Cast[Float](obj).Float64())
} else {
return false
}
case reflect.Complex64, reflect.Complex128:
if obj.IsComplex() {
v.SetComplex(Cast[Complex](obj).Complex128())
} else {
return false
}
case reflect.String:
if obj.IsStr() {
v.SetString(Cast[Str](obj).String())
} else {
return false
}
case reflect.Bool:
if obj.IsBool() {
v.SetBool(Cast[Bool](obj).Bool())
} else {
return false
}
case reflect.Slice:
if v.Type().Elem().Kind() == reflect.Uint8 { // []byte
if obj.IsBytes() {
v.SetBytes(Cast[Bytes](obj).Bytes())
} else {
return false
}
} else {
if obj.IsList() {
list := Cast[List](obj)
l := list.Len()
slice := reflect.MakeSlice(v.Type(), l, l)
for i := 0; i < l; i++ {
item := list.GetItem(i)
ToValue(item, slice.Index(i))
}
v.Set(slice)
} else {
return false
}
}
case reflect.Map:
if obj.IsDict() {
t := v.Type()
v.Set(reflect.MakeMap(t))
dict := Cast[Dict](obj)
dict.ForEach(func(key, value Object) {
vk := reflect.New(t.Key()).Elem()
vv := reflect.New(t.Elem()).Elem()
if !ToValue(key, vk) || !ToValue(value, vv) {
panic(fmt.Errorf("failed to convert key or value to %v", t.Key()))
}
v.SetMapIndex(vk, vv)
})
} else {
return false
}
case reflect.Struct:
if obj.IsDict() {
dict := Cast[Dict](obj)
t := v.Type()
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
key := goNameToPythonName(field.Name)
value := dict.Get(MakeStr(key))
if !ToValue(value, v.Field(i)) {
panic(fmt.Errorf("failed to convert value to %v", field.Name))
}
}
} else {
return false
}
default:
panic(fmt.Errorf("unsupported type conversion from Python object to %v", v.Type()))
}
return true
}
func To[T any](obj Object) (ret T) {
switch any(ret).(type) {
case int8:
return any(int8(Cast[Long](obj).Int64())).(T)
case int16:
return any(int16(Cast[Long](obj).Int64())).(T)
case int32:
return any(int32(Cast[Long](obj).Int64())).(T)
case int64:
return any(Cast[Long](obj).Int64()).(T)
case int:
return any(int(Cast[Long](obj).Int64())).(T)
case uint8:
return any(uint8(Cast[Long](obj).Uint64())).(T)
case uint16:
return any(uint16(Cast[Long](obj).Uint64())).(T)
case uint32:
return any(uint32(Cast[Long](obj).Uint64())).(T)
case uint64:
return any(Cast[Long](obj).Uint64()).(T)
case uint:
return any(uint(Cast[Long](obj).Uint64())).(T)
case float32:
return any(float32(Cast[Float](obj).Float64())).(T)
case float64:
return any(Cast[Float](obj).Float64()).(T)
case complex64:
return any(complex64(Cast[Complex](obj).Complex128())).(T)
case complex128:
return any(Cast[Complex](obj).Complex128()).(T)
case string:
return any(Cast[Str](obj).String()).(T)
case bool:
return any(Cast[Bool](obj).Bool()).(T)
case []byte:
return any(Cast[Bytes](obj).Bytes()).(T)
default:
v := reflect.ValueOf(ret)
switch v.Kind() {
case reflect.Slice:
return toSlice[T](obj, v)
}
panic(fmt.Errorf("unsupported type conversion from Python object to %T", ret))
}
}
func toSlice[T any](obj Object, v reflect.Value) T {
list := Cast[List](obj)
l := list.Len()
v = reflect.MakeSlice(v.Type(), l, l)
for i := 0; i < l; i++ {
v.Index(i).Set(reflect.ValueOf(To[T](list.GetItem(i))))
}
return v.Interface().(T)
}
func fromSlice(v reflect.Value) List {
l := v.Len()
list := newList(C.PyList_New(C.Py_ssize_t(l)))
for i := 0; i < l; i++ {
list.SetItem(i, From(v.Index(i).Interface()))
}
return list
}
func fromMap(v reflect.Value) Dict {
dict := newDict(C.PyDict_New())
iter := v.MapRange()
for iter.Next() {
dict.Set(From(iter.Key().Interface()), From(iter.Value().Interface()))
}
return dict
}
func fromStruct(v reflect.Value) Object {
ty := v.Type()
if typeObj, ok := pyTypeMap[ty]; ok {
obj := newObject(C._PyObject_New((*C.PyTypeObject)(unsafe.Pointer(typeObj))))
for i := 0; i < ty.NumField(); i++ {
field := ty.Field(i)
key := goNameToPythonName(field.Name)
obj.SetAttr(key, From(v.Field(i).Interface()))
}
return obj
}
dict := newDict(C.PyDict_New())
for i := 0; i < ty.NumField(); i++ {
field := ty.Field(i)
key := goNameToPythonName(field.Name)
dict.Set(MakeStr(key).Object, From(v.Field(i).Interface()))
}
return dict.Object
}