Source

pyd / infrastructure / pyd / make_object.d

   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
/*
Copyright 2006, 2007 Kirk McDonald

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/++
  This module contains some useful type conversion functions. The two
  most interesting operations here are python_to_d and d_to_python.
 
  Additionally, the py function is provided as a convenience to directly 
  convert a D object into an instance of PydObject.

  To convert a PydObject to a D type, use PydObject.to_d.
 +/
module pyd.make_object;

import deimos.python.Python;

import std.array;
import std.algorithm;
import std.complex;
import std.typetuple;
import std.bigint;
import std.traits;
import std.typecons;
import std.metastrings;
import std.conv;
import std.range;

import pyd.pydobject;
import pyd.class_wrap;
import pyd.struct_wrap;
import pyd.func_wrap;
import pyd.def;
import pyd.exception;


shared static this() {
    on_py_init( {
            add_module!(
                ModuleName!"pyd", 
                Docstring!"contains some wrapper utilities")();
            });
    on_py_init( {
            wrap_struct!(RangeWrapper,
                ModuleName!"pyd",
                Def!(RangeWrapper.iter, PyName!"__iter__"),
                Def!(RangeWrapper.next))();
            }, PyInitOrdering.After);
}

class to_conversion_wrapper(dg_t) {
    alias ParameterTypeTuple!(dg_t)[0] T;
    alias ReturnType!(dg_t) Intermediate;
    dg_t dg;
    this(dg_t fn) { dg = fn; }
    PyObject* opCall(T t) {
        static if (is(Intermediate == PyObject*)) {
            return dg(t);
        } else {
            return d_to_python(dg(t));
        }
    }
}
class from_conversion_wrapper(dg_t) {
    alias ParameterTypeTuple!(dg_t)[0] Intermediate;
    alias ReturnType!(dg_t) T;
    dg_t dg;
    this(dg_t fn) { dg = fn; }
    T opCall(PyObject* o) {
        static if (is(Intermediate == PyObject*)) {
            return dg(o);
        } else {
            return dg(python_to_d!(Intermediate)(o));
        }
    }
}

template to_converter_registry(From) {
    PyObject* delegate(From) dg=null;
}
template from_converter_registry(To) {
    To delegate(PyObject*) dg=null;
}

/**
Extend pyd's conversion mechanism. Will be used by d_to_python only if d_to_python cannot 
convert its argument by regular means.

Params:
dg = A callable which takes a D type and returns a PyObject*, or any 
type convertible by d_to_python.
*/
void ex_d_to_python(dg_t) (dg_t dg) {
    static if (is(dg_t == delegate) && is(ReturnType!(dg_t) == PyObject*)) {
        to_converter_registry!(ParameterTypeTuple!(dg_t)[0]).dg = dg;
    } else {
        auto o = new to_conversion_wrapper!(dg_t)(dg);
        to_converter_registry!(typeof(o).T).dg = &o.opCall;
    }
}

/**
Extend pyd's conversion mechanims. Will be used by python_to_d only if python_to_d 
cannot convert its argument by regular means.

Params:
dg = A callable which takes a PyObject*, or any type convertible by python_to_d,
    and returns a D type.
*/
void ex_python_to_d(dg_t) (dg_t dg) {
    static if (is(dg_t == delegate) && is(ParameterTypeTuple!(dg_t)[0] == PyObject*)) {
        from_converter_registry!(ReturnType!(dg_t)).dg = dg;
    } else {
        auto o = new from_conversion_wrapper!(dg_t)(dg);
        from_converter_registry!(typeof(o).T).dg = &o.opCall;
    }
}

/**
 * Returns a new (owned) reference to a Python object based on the passed
 * argument. If the passed argument is a PyObject*, this "steals" the
 * reference. (In other words, it returns the PyObject* without changing its
 * reference count.) If the passed argument is a PydObject, this returns a new
 * reference to whatever the PydObject holds a reference to.
 *
 * If the passed argument can't be converted to a PyObject, a Python
 * RuntimeError will be raised and this function will return null.
 */
PyObject* d_to_python(T) (T t) {
    static if (!is(T == PyObject*) && is(typeof(t is null)) &&
            !isAssociativeArray!T && !isArray!T) {
        if (t is null) {
            return Py_INCREF(Py_None());
        }
    }
    static if (isBoolean!T) {
        return Py_INCREF(t ? Py_True : Py_False);
    } else static if(isIntegral!T) {
        static if(isUnsigned!T) {
            return PyLong_FromUnsignedLongLong(t);
        }else static if(isSigned!T) {
            return PyLong_FromLongLong(t);
        }
    } else static if (isFloatingPoint!T) {
        return PyFloat_FromDouble(t);
    } else static if( isTuple!T) {
        T.Types tuple;
        foreach(i, _t; T.Types) {
            tuple[i] = t[i];
        }
        return PyTuple_FromItems(tuple);
    } else static if (is(Unqual!T _unused : Complex!F, F)) {
        return PyComplex_FromDoubles(t.re, t.im);
    } else static if(is(T == std.bigint.BigInt)) {
        import std.string: format = xformat;
        string num_str = format("%s\0",t);
        return PyLong_FromString(num_str.dup.ptr, null, 10);
    } else static if(is(Unqual!T _unused : PydInputRange!E, E)) {
        return Py_INCREF(t.ptr);
    } else static if(isSomeString!T) {
        alias Unqual!(typeof(T.init[0])) C;
        static if(is(C == char)) {
            return PyUnicode_DecodeUTF8(t.ptr, t.length, null);
        }else static if(is(C == wchar)) {
            return PyUnicode_DecodeUTF16(cast(char*) t.ptr, 
                    2*t.length, null, null);
        }else static if(is(C == dchar)) {
            return PyUnicode_DecodeUTF32(cast(char*) t.ptr, 
                    4*t.length, null, null);
        }else static assert(false, "waht is this T? " ~ T.stringof);
    } else static if (isArray!(T)) {
        // Converts any array (static or dynamic) to a Python list
        PyObject* lst = PyList_New(t.length);
        PyObject* temp;
        if (lst is null) return null;
        for(int i=0; i<t.length; ++i) {
            temp = d_to_python(t[i]);
            if (temp is null) {
                Py_DECREF(lst);
                return null;
            }
            // Steals the reference to temp
            PyList_SET_ITEM(lst, i, temp);
        }
        return lst;
    // Converts any associative array to a Python dict
    } else static if (isAssociativeArray!(T)) {
        PyObject* dict = PyDict_New();
        PyObject* ktemp, vtemp;
        int result;
        if (dict is null) return null;
        foreach(k, v; t) {
            ktemp = d_to_python(k);
            vtemp = d_to_python(v);
            if (ktemp is null || vtemp is null) {
                if (ktemp !is null) Py_DECREF(ktemp);
                if (vtemp !is null) Py_DECREF(vtemp);
                Py_DECREF(dict);
                return null;
            }
            result = PyDict_SetItem(dict, ktemp, vtemp);
            Py_DECREF(ktemp);
            Py_DECREF(vtemp);
            if (result == -1) {
                Py_DECREF(dict);
                return null;
            }
        }
        return dict;
    } else static if (is(T == delegate) || is(T == function)) {
        PydWrappedFunc_Ready!(T)();
        return WrapPyObject_FromObject(t);
    } else static if (is(T : PydObject)) {
        return Py_INCREF(t.ptr());
    // The function expects to be passed a borrowed reference and return an
    // owned reference. Thus, if passed a PyObject*, this will increment the
    // reference count.
    } else static if (is(T : PyObject*)) {
        Py_XINCREF(t);
        return t;
    // Convert wrapped type to a PyObject*
    } else static if (is(T == class)) {
        // But only if it actually is a wrapped type. :-)
        PyTypeObject** type = t.classinfo in wrapped_classes;
        if (type) {
            return WrapPyObject_FromTypeAndObject(*type, t);
        }
        // If it's not a wrapped type, fall through to the exception.
    // If converting a struct by value, create a copy and wrap that
    } else static if (is(T == struct) && isInputRange!T) {
        return d_to_python(wrap_range(t));
    } else static if (is(T == struct)) {
        if (is_wrapped!(T*)) {
            T* temp = new T;
            *temp = t;
            return WrapPyObject_FromObject(temp);
        }
    // If converting a struct by reference, wrap the thing directly
    } else static if (is(typeof(*t) == struct)) {
        if (is_wrapped!(T)) {
            if (t is null) {
                return Py_INCREF(Py_None());
            }
            return WrapPyObject_FromObject(t);
        }
    }
    // No conversion found, check runtime registry
    if (to_converter_registry!(T).dg) {
        return to_converter_registry!(T).dg(t);
    }
    PyErr_SetString(PyExc_RuntimeError, ("D conversion function d_to_python failed with type " ~ typeid(T).toString()).ptr);
    return null;
}

/**
 * Helper function for creating a PyTuple from a series of D items.
 */
PyObject* PyTuple_FromItems(T ...)(T t) {
    PyObject* tuple = PyTuple_New(t.length);
    PyObject* temp;
    if (tuple is null) return null;
    foreach(i, arg; t) {
        temp = d_to_python(arg);
        if (temp is null) {
            Py_DECREF(tuple);
            return null;
        }
        PyTuple_SetItem(tuple, i, temp);
    }
    return tuple;
}

/**
 * Constructs an object based on the type of the argument passed in.
 *
 * For example, calling py(10) would return a PydObject holding the value 10.
 *
 * Calling this with a PydObject will return back a reference to the very same
 * PydObject.
 */
PydObject py(T) (T t) {
    static if(is(T : PydObject)) {
        return t;
    } else {
        return new PydObject(d_to_python(t));
    }
}

/**
 * An exception class used by python_to_d.
 */
class PydConversionException : Exception {
    this(string msg, string file = __FILE__, size_t line = __LINE__) { 
        super(msg, file, line); 
    }
}

/**
 * This converts a PyObject* to a D type. The template argument is the type to
 * convert to. The function argument is the PyObject* to convert. For instance:
 *
 *$(D_CODE PyObject* i = PyInt_FromLong(20);
 *int n = _python_to_d!(int)(i);
 *assert(n == 20);)
 *
 * This throws a PydConversionException if the PyObject can't be converted to
 * the given D type.
 */
T python_to_d(T) (PyObject* o) {
    // This ordering is somewhat important. The checks for Tuple and Complex
    // must be before the check for general structs.

    static if (is(PyObject* : T)) {
        return o;
    } else static if (is(PydObject : T)) {
        return new PydObject(borrowed(o));
    } else static if (is(T == void)) {
        if (o != cast(PyObject*) Py_None()) could_not_convert!(T)(o);
        return;
    } else static if (isTuple!T) {
        T.Types tuple;
        if(!PyTuple_Check(o)) could_not_convert!T(o);
        auto len = PyTuple_Size(o);
        if(len != T.Types.length) could_not_convert!T(o);
        foreach(i,_t; T.Types) {
            auto obj =  Py_XINCREF(PyTuple_GetItem(o, i));
            tuple[i] = python_to_d!_t(obj);
            Py_DECREF(obj);
        }
        return T(tuple);
    } else static if (is(Unqual!T _unused : Complex!F, F)) {
        double real_ = PyComplex_RealAsDouble(o);
        handle_exception();
        double imag = PyComplex_ImagAsDouble(o);
        handle_exception();
        return complex!(F,F)(real_, imag);
    } else static if(is(Unqual!T == std.bigint.BigInt)) {
        if (!PyNumber_Check(o)) could_not_convert!(T)(o);
        string num_str = python_to_d!string(o);
        if(num_str.endsWith("L")) num_str = num_str[0..$-1];
        return BigInt(num_str);
    } else static if(is(Unqual!T _unused : PydInputRange!E, E)) {
        return cast(T) PydInputRange!E(borrowed(o));
    } else static if (is(T == class)) {
        // We can only convert to a class if it has been wrapped, and of course
        // we can only convert the object if it is the wrapped type.
        if (
            is_wrapped!(T) &&
            PyObject_IsInstance(o, cast(PyObject*)&wrapped_class_type!(T)) &&
            cast(T)((cast(wrapped_class_object!(Object)*)o).d_obj) !is null
        ) {
            return WrapPyObject_AsObject!(T)(o);
        }
        // Otherwise, throw up an exception.
        //could_not_convert!(T)(o);
    } else static if (is(T == struct)) { // struct by value
        // struct is wrapped
        if (is_wrapped!(T*) && PyObject_TypeCheck(o, &wrapped_class_type!(T*))) { 
            return *WrapPyObject_AsObject!(T*)(o);
        }
        // or struct is wrapped range
        if(PyObject_IsInstance(o, 
                    cast(PyObject*)&wrapped_class_type!(RangeWrapper*))) {
            RangeWrapper* wrapper = WrapPyObject_AsObject!(RangeWrapper*)(o);
            if(typeid(T) != wrapper.tid) {
                could_not_convert!T(o, format("typeid mismatch: %s vs %s", 
                            wrapper.tid, typeid(T)));
            }
            T t = *cast(T*) wrapper.range;
            return t;
        }
    } else static if (isPointer!T && is(pointerTarget!T == struct)) { 
        // pointer to struct   
        if (is_wrapped!(T) && PyObject_TypeCheck(o, &wrapped_class_type!(T))) {
            return WrapPyObject_AsObject!(T)(o);
        }// else could_not_convert!(T)(o);
    } else static if (is(T == delegate)) {
        // Get the original wrapped delegate out if this is a wrapped delegate
        if (is_wrapped!(T) && PyObject_TypeCheck(o, &wrapped_class_type!(T))) {
            return WrapPyObject_AsObject!(T)(o);
        // Otherwise, wrap the PyCallable with a delegate
        } else if (PyCallable_Check(o)) {
            return PydCallable_AsDelegate!(T)(o);
        }// else could_not_convert!(T)(o);
    } else static if (is(T == function)) {
        // We can only make it a function pointer if we originally wrapped a
        // function pointer.
        if (is_wrapped!(T) && PyObject_TypeCheck(o, &wrapped_class_type!(T))) {
            return WrapPyObject_AsObject!(T)(o);
        }// else could_not_convert!(T)(o);
    } else static if (isSomeString!T) {
        alias Unqual!(typeof(T.init[0])) C;
        PyObject* str;
        if(PyBytes_Check(o)) {
            static if(is(C == char)) {
                str = o;
            }else{
                version(Python_3_0_Or_Later) {
                    str = PyObject_Str(o);
                    if(!str) handle_exception();
                }else{
                    str = PyObject_Unicode(o);
                    if(!str) handle_exception();
                }
            }
        }else if(PyUnicode_Check(o)) {
            str = o;
        }else {
            str = PyObject_Repr(o);
            if(!str) handle_exception();
            version(Python_3_0_Or_Later) {
            }else{
                static if(!is(C == char)) {
                    str = PyObject_Unicode(str);
                    if(!str) handle_exception();
                }
            }
        }
        static if(is(C == char)) {
            if(PyBytes_Check(str)) {
                const(char)* res = PyBytes_AsString(str);
                if(!res) handle_exception();
                return to!T(res);
            }
        }

        if(PyUnicode_Check(str)) {
            static if(is(C == char)) {
                PyObject* utf8 = PyUnicode_AsUTF8String(str);
                if(!utf8) handle_exception();
                const(char)* res = PyBytes_AsString(utf8);
                if(!res) handle_exception();
                return to!T(res);
            }else static if(is(C == wchar)) {
                PyObject* utf16 = PyUnicode_AsUTF16String(str);
                if(!utf16) handle_exception();
                // PyUnicode_AsUTF16String puts a BOM character in front of
                // string
                auto ptr = cast(const(wchar)*)(PyBytes_AsString(utf16)+2);
                Py_ssize_t len = PyBytes_Size(utf16)/2-1; 
                wchar[] ws = new wchar[](len);
                ws[] = ptr[0 .. len];
                return cast(T) ws;
            }else static if(is(C == dchar)) {
                PyObject* utf32 = PyUnicode_AsUTF32String(str);
                if(!utf32) handle_exception();
                // PyUnicode_AsUTF32String puts a BOM character in front of
                // string
                auto ptr = cast(const(dchar)*)(PyBytes_AsString(utf32)+4);
                Py_ssize_t len = PyBytes_Size(utf32)/4-1; 
                dchar[] ds = new dchar[](len);
                ds[] = ptr[0 .. len];
                return cast(T) ds;
            }else static assert(false, "what T is this!? " ~ T.stringof);
        }
        assert(0);
    } else static if (isArray!T || IsStaticArrayPointer!T) {
        static if(isPointer!T)
            alias Unqual!(ElementType!(pointerTarget!T)) E;
        else
            alias Unqual!(ElementType!T) E;
        version(Python_2_6_Or_Later) {
            if(PyObject_CheckBuffer(o)) {
                return python_buffer_to_d!(T)(o);
            }
        }
        if(o.ob_type is array_array_Type) {
            return python_array_array_to_d!T(o);
        }else {
            return python_iter_to_d!T(o);
        }
    } else static if (isFloatingPoint!T) {
        double res = PyFloat_AsDouble(o);
        handle_exception();
        return cast(T) res;
    } else static if(isIntegral!T) {
        version(Python_3_0_Or_Later) {
        }else{
            if(PyInt_Check(o)) {
                C_long res = PyInt_AsLong(o);
                handle_exception();
                static if(isUnsigned!T) {
                    if(res < 0) could_not_convert!T(o, format("%s out of bounds [%s, %s]", res, 0, T.max));
                    if(T.max < res) could_not_convert!T(o,format("%s out of bounds [%s, %s]", res, 0, T.max));
                    return cast(T) res;
                }else static if(isSigned!T) {
                    if(T.min > res) could_not_convert!T(o, format("%s out of bounds [%s, %s]", res, T.min, T.max)); 
                    if(T.max < res) could_not_convert!T(o, format("%s out of bounds [%s, %s]", res, T.min, T.max)); 
                    return cast(T) res;
                }
            }
        }
        if(PyLong_Check(o)) {
            static if(isUnsigned!T) {
                static assert(T.sizeof <= C_ulonglong.sizeof);
                C_ulonglong res = PyLong_AsUnsignedLongLong(o);
                handle_exception();
                // no overflow from python to C_ulonglong,
                // overflow from C_ulonglong to T?
                if(T.max < res) could_not_convert!T(o); 
                return cast(T) res;
            }else static if(isSigned!T) {
                static assert(T.sizeof <= C_longlong.sizeof);
                C_longlong res = PyLong_AsLongLong(o);
                handle_exception();
                // no overflow from python to C_longlong,
                // overflow from C_longlong to T?
                if(T.min > res) could_not_convert!T(o); 
                if(T.max < res) could_not_convert!T(o); 
                return cast(T) res;
            }
        }
    } else static if (isBoolean!T) {
        if (!PyNumber_Check(o)) could_not_convert!(T)(o);
        int res = PyObject_IsTrue(o);
        handle_exception();
        return res == 1;
    }

    if (from_converter_registry!(T).dg) {
        return from_converter_registry!(T).dg(o);
    }
    could_not_convert!(T)(o);
    assert(0);
}

// (*^&* array doesn't implement the buffer interface, but we still
// want it to copy fast.
/// Convert an array.array object to a D object.
///
/// Used by python_to_d.
T python_array_array_to_d(T)(PyObject* o) 
if(isArray!T || IsStaticArrayPointer!T) {
    static if(isPointer!T)
        alias Unqual!(ElementType!(pointerTarget!T)) E;
    else
        alias Unqual!(ElementType!T) E;
    if(o.ob_type !is array_array_Type)
        could_not_convert!T(o, "not an array.array");
    arrayobject* arr_o = cast(arrayobject*) o;
    // array.array's data can be got with a single memcopy.
    enforce(arr_o.ob_descr, "array.ob_descr null!");
    char typecode = cast(char) arr_o.ob_descr.typecode;
    if(!match_format_type!E(""~typecode)) {
        could_not_convert!T(o, format("item mismatch: '%s' vs %s",
                    typecode, E.stringof));
    }

    int itemsize = arr_o.ob_descr.itemsize;
    if(itemsize != E.sizeof) 
        could_not_convert!T(o,
                format("item size mismatch: %s vs %s", 
                    itemsize, E.sizeof));
    Py_ssize_t count = Py_SIZE(arr_o);
    if(count < 0) 
        could_not_convert!T(o, format("nonsensical array length: %s", 
                    count));
    MatrixInfo!T.unqual _array;
    static if(isDynamicArray!T) {
        _array = new MatrixInfo!T.unqual(count);
    }else {
        if(!MatrixInfo!T.check([count])) 
            could_not_convert!T(o, 
                    format("length mismatch: %s vs %s", count, T.length));
    }
    // copy data, don't take slice
    memcpy(_array.ptr, arr_o.ob_item, count*itemsize);
    //_array[] = cast(E[]) arr_o.ob_item[0 .. count*itemsize];
    return cast(T) _array;
}

/**
  Convert a d array to a python array.array.
  array.array does not support 8 byte integers.

  Not used by d_to_python.
  */
PyObject* d_to_python_array_array(T)(T t) 
if((isArray!T || IsStaticArrayPointer!T) &&
        MatrixInfo!T.ndim == 1 &&
        SimpleFormatType!(MatrixInfo!T.MatrixElementType).supported) {

    alias MatrixInfo!T.MatrixElementType ME;
    string format = SimpleFormatType!ME.s;
    version(Python_3_0_Or_Later) {
        PyObject* pyformat = d_to_python(format);
    }else{
        // stinking py2 array won't take unicode
        PyObject* pyformat = PyString_FromStringAndSize(format.ptr, format.length);
    }
    PyObject* args = PyTuple_New(1);
    PyTuple_SetItem(args, 0, pyformat);
    scope(exit) Py_DECREF(args);
    PyObject* obj = array_array_Type.tp_new(array_array_Type, args, null);
    if(!obj) handle_exception();
    arrayobject* arr_o = cast(arrayobject*) obj;
    Py_ssize_t[] shape = MatrixInfo!T.build_shape(t);
    size_t datalen = ME.sizeof*shape[0];
    Py_SET_SIZE(arr_o, shape[0]);
    void* data = PyMem_Malloc(datalen);
    static if(isPointer!T) {
        memcpy(data, t, datalen);
    }else {
        memcpy(data, t.ptr, datalen);
    }
    arr_o.ob_item = cast(ubyte*) data;
    return obj;
}

/** Convert an iterable Python object to a D object.
  *
  * Used by python_to_d.
  */
T python_iter_to_d(T)(PyObject* o) if(isArray!T || IsStaticArrayPointer!T) {
    static if(isPointer!T)
        alias Unqual!(ElementType!(pointerTarget!T)) E;
    else
        alias Unqual!(ElementType!T) E;
    PyObject* iter = PyObject_GetIter(o);
    if (iter is null) {
        PyErr_Clear();
        could_not_convert!(T)(o);
    }
    scope(exit) Py_DECREF(iter);
    Py_ssize_t len = PyObject_Length(o);
    if (len == -1) {
        PyErr_Clear();
        could_not_convert!(T)(o);
    }

    MatrixInfo!T.unqual _array;
    static if(isDynamicArray!T) {
        _array = new MatrixInfo!T.unqual(len);
    }else static if(isStaticArray!T){
        if(len != T.length) 
            could_not_convert!T(o, 
                    format("length mismatch: %s vs %s", 
                        len, T.length));
    }else static if(isPointer!T){
        ubyte[] bufi = new ubyte[](pointerTarget!T.sizeof);
        _array = cast(MatrixInfo!T.unqual)(bufi.ptr);
    }
    int i = 0;
    PyObject* item = PyIter_Next(iter);
    while (item) {
        try {
            _array[i] = python_to_d!(E)(item);
        } catch(PydConversionException e) {
            Py_DECREF(item);
            // We re-throw the original conversion exception, rather than
            // complaining about being unable to convert to an array. The
            // partially constructed array is left to the GC.
            throw e;
        }
        ++i;
        Py_DECREF(item);
        item = PyIter_Next(iter);
    }
    return cast(T) _array;
}

version(Python_2_6_Or_Later) {
/// Convert a Python new-style buffer to a D object.
///
/// Used by python_to_d.
T python_buffer_to_d(T)(PyObject* o) 
if (isArray!T || IsStaticArrayPointer!T) {
    PydObject bob = new PydObject(borrowed(o));
    auto buf = bob.buffer_view();
    alias MatrixInfo!T.MatrixElementType ME;
    MatrixInfo!T.unqual _array;
    /+
    if(buf.itemsize != ME.sizeof)
        could_not_convert!T(o, format("item size mismatch: %s vs %s",
                    buf.itemsize, ME.sizeof));
    +/
    if(!match_format_type!ME(buf.format)) {
        could_not_convert!T(o, format("item type mismatch: '%s' vs %s",
                    buf.format, ME.stringof));
    }
    if(buf.has_nd) {
        if(!MatrixInfo!T.check(buf.shape)) 
            could_not_convert!T(o,
                    format("dimension mismatch: %s vs %s",
                        buf.shape, MatrixInfo!T.dimstring));
        if(buf.c_contiguous) {
            // woohoo! single memcpy 
            static if(MatrixInfo!T.isRectArray && isStaticArray!T) {
                memcpy(_array.ptr, buf.buf.ptr, buf.buf.length);
            }else{
                alias MatrixInfo!T.RectArrayType RectArrayType;
                static if(!isStaticArray!(RectArrayType)) {
                    ubyte[] dbuf = new ubyte[](buf.buf.length);
                    memcpy(dbuf.ptr, buf.buf.ptr, buf.buf.length);
                }
                size_t rectsize = ME.sizeof;
                size_t MErectsize = 1;
                foreach(i; MatrixInfo!T.rectArrayAt .. MatrixInfo!T.ndim) {
                    rectsize *= buf.shape[i];
                    MErectsize *= buf.shape[i];
                }
                static if(MatrixInfo!T.isRectArray) {
                    static if(isPointer!T)
                        _array = cast(typeof(_array)) dbuf.ptr;
                    else {
                        static assert(isDynamicArray!T);
                        _array = cast(typeof(_array)) dbuf;
                    }
                }else{
                    // rubbish. much pointer pointing
                    size_t offset = 0;
                    static if(isDynamicArray!T) {
                        _array = new MatrixInfo!T.unqual(buf.shape[0]);
                    }
                    enum string xx = (MatrixInfo!T.matrixIter(
                        "_array", "buf.shape", "_indeces",
                        MatrixInfo!T.rectArrayAt, q{
                    static if(isDynamicArray!(typeof($array_ixn))) {
                        $array_ixn = new typeof($array_ixn)(buf.shape[$i+1]);
                    }
                    static if(is(typeof($array_ixn) == RectArrayType)) {
                        // should be innermost loop
                        assert(offset + rectsize <= buf.buf.length, 
                                "uh oh: overflow!");
                        alias typeof($array_ixn) rectarr;
                        static if(isStaticArray!rectarr) {
                            memcpy($array_ixn.ptr, buf.buf.ptr + offset, rectsize);
                        }else{
                            static assert(isDynamicArray!rectarr);
                        
                            $array_ixn = (cast(typeof($array_ixn.ptr))(dbuf.ptr + offset))
                                [0 .. MErectsize];
                        }
                        offset += rectsize;
                    }
                        },
                        ""));
                    mixin(xx);
                }
            }
        }else if(buf.fortran_contiguous) {
            // really rubbish. no memcpy.
            static if(isDynamicArray!T) {
                _array = new MatrixInfo!T.unqual(buf.shape[0]);
            }else static if(isPointer!T) {
                ubyte[] dubuf = new ubyte[](buf.buf.length);
                _array = cast(typeof(_array)) dubuf.ptr;
                    
            }
            enum string xx = (MatrixInfo!T.matrixIter(
                "_array", "buf.shape", "_indeces",
                MatrixInfo!T.ndim, q{
                static if(isDynamicArray!(typeof($array_ixn))) {
                    $array_ixn = new typeof($array_ixn)(buf.shape[$i+1]);
                }else static if(is(typeof($array_ixn) == ME)) {
                    $array_ixn = buf.item!ME(cast(Py_ssize_t[]) _indeces);
                }
                },
                ""));
            mixin(xx);
        }else {
            // wut?
            could_not_convert!T(o,("todo: know what todo"));
            assert(0);
        }
        return cast(T) _array;
    }else if(buf.has_simple) {
        /*
           static if(isDynamicArray!T) {
           E[] array = new E[](buf.buf.length);
           }else static if(isStaticArray!T) {
           if(buf.buf.length != T.length) 
           could_not_convert!T(o, 
           format("length mismatch: %s vs %s", 
           buf.buf.length, T.length));
           E[T.length] array;
           }
           return cast(T) array;
         */
        assert(0, "py jingo wat we do here?");
    }
    return cast(T) _array;
}
}

/**
  Wrap a D input range as a python iterator object.

  Does not work for UFCS ranges (e.g. arrays), classes
  */
auto wrap_range(Range)(Range range) if(is(Range == struct)) {
    import core.memory;
    RangeWrapper wrap;
    // the hackery! the hackery!
    Range* keeper = cast(Range*) GC.calloc(Range.sizeof);
    std.algorithm.move(range, *keeper);
    wrap.range = cast(void*) keeper;
    wrap.tid = typeid(Range);
    wrap.empty = cast(int delegate(void*)) dg_wrapper(keeper, &Range.empty);
    wrap.popFront = cast(void delegate(void*)) dg_wrapper(keeper, &Range.popFront);
    auto front_dg = cast(ElementType!Range delegate(Range*)) 
        dg_wrapper(keeper, cast(ElementType!Range function()) &Range.front);
    wrap.front = delegate PyObject*(void* a) {
        return d_to_python(front_dg(cast(Range*)a));
    };
    return wrap;
}

/**
  Wrapper type wrapping a D input range as a python iterator object

  Lives in reserved python module "pyd".
  */
struct RangeWrapper {
    void* range;
    void delegate(void*) popFront;
    PyObject* delegate(void*) front;
    int delegate(void*) empty;
    TypeInfo tid;

    RangeWrapper* iter() {
        return &this;
    }
    PyObject* next() {
        if(this.empty(range)) {
            return null;
        }else {
            auto result = d_to_python(this.front(range));
            this.popFront(range);
            return result;
        }
    }
}

/// Check T against format
/// See_Also:
/// <a href='http://docs.python.org/library/struct.html#struct-format-strings'>
/// Struct Format Strings </a>
bool match_format_type(T)(string format) {
    alias T S;
    enforce(format.length > 0);

    bool native_size = false;
    switch(format[0]) {
        case '@':
            // this (*&^& function is not defined
            //PyBuffer_SizeFromFormat()
            native_size = true;
        case '=','<','>','!':
            format = format[1 .. $];
        default:
            break;
    }
    // by typeishness
    switch(format[0]) {
        case 'x', 's', 'p': 
            // don't support these
            enforce(false, "unsupported format: " ~ format); 
        case 'c': 
            break;
        case 'b', 'h','i','l','q': 
            if(!isSigned!S) return false;
            break;
        case 'B', 'H', 'I', 'L','Q': 
            if(!isUnsigned!S) return false;
            break;
        case 'f','d':
            if(!isFloatingPoint!S) return false;
            break;
        case '?': 
            if(!isBoolean!S) return false;
        default:
            enforce(false, "unknown format: " ~ format); 
    }

    // by sizeishness
    if(native_size) {
        // grr
        assert(0, "todo");
    }else{
        switch(format[0]) {
            case 'c','b','B','?':
                return (S.sizeof == 1);
            case 'h','H':
                return (S.sizeof == 2);
            case 'i','I','l','L','f':
                return (S.sizeof == 4);
            case 'q','Q','d':
                return (S.sizeof == 8);
            default:
                enforce(false, "unknown format: " ~ format); 
                assert(0); // seriously, d?
                
        }
    }
}

/// generate a struct format string from T
template SimpleFormatType(T) {
    static if(isFloatingPoint!T) {
        static if(T.sizeof == 4) {
            enum s = "f";
            enum supported = true;
        }else static if(T.sizeof == 8) {
            enum s = "d";
            enum supported = true;
        }else{
            enum supported = false;
        }
    }else static if(isBoolean!T) {
        enum s = "?";
        enum supported = true;
    }else static if(isIntegral!T) {
        static if(isSigned!T) {
            static if(T.sizeof == 1) {
                enum s = "b";
                enum supported = true;
            }else static if(T.sizeof == 2) {
                enum s = "h";
                enum supported = true;
            }else static if(T.sizeof == 4) {
                enum s = "i";
                enum supported = true;
            }else static if(T.sizeof == 8) {
                enum s = "q";
                enum supported = true;
            }else {
                enum supported = false;
                enum supported = true;
            }
        }else static if(isUnsigned!T) {
            static if(T.sizeof == 1) {
                enum s = "B";
                enum supported = true;
            }else static if(T.sizeof == 2) {
                enum s = "H";
                enum supported = true;
            }else static if(T.sizeof == 4) {
                enum s = "I";
                enum supported = true;
            }else static if(T.sizeof == 8) {
                enum s = "Q";
                enum supported = true;
            }else {
                enum supported = false;
            }
        }
    }else {
        enum supported = false;
    }
}

/**
  Check that T is a pointer to a rectangular static array.
  */
template IsStaticArrayPointer(T) {
    template _Inner(S) {
        static if(isStaticArray!S) {
            enum _Inner = _Inner!(ElementType!S);
        } else static if(isArray!S || isPointer!S) {
            enum _Inner = false;
        }else {
            enum _Inner = true;
        }
    }
    static if(isPointer!T) {
        enum bool IsStaticArrayPointer = _Inner!(pointerTarget!T);
    }else{
        enum bool IsStaticArrayPointer = false;
    }
}

/**
  Some reflective information about multidimensional arrays

  Handles dynamic arrays, static arrays, and pointers to static arrays.
*/
template MatrixInfo(T) if(isArray!T || IsStaticArrayPointer!T) {
    template _dim_list(T, dimi...) {
        static if(isDynamicArray!T) {
            alias _dim_list!(ElementType!T, dimi,-1) next;
            alias next.list list;
            alias next.elt elt;
            alias next.unqual[] unqual;
        }else static if(isStaticArray!T) {
            alias _dim_list!(ElementType!T, dimi, cast(Py_ssize_t) T.length) next;
            alias next.list list;
            alias next.elt elt;
            alias next.unqual[T.length] unqual;
        }else {
            alias dimi list;
            alias T elt;
            alias Unqual!T unqual;
        }
    }

    string tuple2string(T...)() {
        string s = "[";
        foreach(i, t; T) {
            if(t == -1) s ~= "*";
            else s ~= to!string(t);
            if(i == T.length-1) {
                s ~= "]";
            }else{
                s ~= ",";
            }
        }
        return s;
    }

    /**
      Build shape from t. Assumes all arrays in a dimension are initialized 
      and of uniform length.
      */
    Py_ssize_t[] build_shape(T t) {
        Py_ssize_t[] shape = new Py_ssize_t[](ndim);
        mixin(shape_builder_mixin("t", "shape"));
        return shape;
    }

    string shape_builder_mixin(string arr_name, string shape_name) {
        static if(isPointer!T) {
            string s_ixn = "(*" ~ arr_name ~ ")";
        }else{
            string s_ixn = arr_name;
        }
        string s = "";
        foreach(i; 0 .. ndim) {
            s ~= shape_name ~ "["~ to!string(i) ~"] = " ~ s_ixn ~ ".length;";
            s_ixn ~= "[0]";
        }
        return s;
    }

    /**
      Ensures that T can store a matrix of _shape shape.
      */
    bool check(Py_ssize_t[] shape) {
        if (shape.length != dim_list.length) return false;
        foreach(i, d; dim_list) {
            if(dim_list[i] == -1) continue;
            if(d != shape[i]) return false;
        }
        return true;
    }

/**
Generate a mixin string of nested for loops that iterate over the
first ndim dimensions of an array of type T (or, preferrably 
MatrixInfo!T.unqual).

Params:
arr_name = name of array to iterate. 
shape_name = name of array of dimension lengths.
index_name = name to use for index vector. Declared in a new nested scoped.
ndim = number of dimensions to iterate over.
pre_code = code to mixin each for loop before beginning the nested for loop.
post_code = code to mix in to each for loop after finishing the nested for loop.
*/

    string matrixIter(string arr_name, string shape_name, 
            string index_name,
            size_t ndim, 
            string pre_code, string post_code) {
        string s_begin = "{\n";
        string s_end = "}\n";
        static if(isPointer!T) {
            string s_ixn = "(*" ~ arr_name ~ ")";
        }else{
            string s_ixn = arr_name;
        }

        s_begin ~= "size_t[" ~ to!string(ndim) ~ "] " ~ index_name ~ ";\n";
        foreach(i; 0 .. ndim) {
            string s_i = to!string(i);
            s_ixn ~= "["~ index_name ~ "[" ~ s_i ~ "]]";
            string index = index_name~ "[" ~ s_i ~ "]";
            string shape_i = shape_name ~ "[" ~ s_i ~ "]";
            s_begin ~= "for("~index~" = 0;" ~index ~ " < " ~ shape_i ~ 
                "; " ~ index ~ "++) {";
            s_end ~= "}\n";

            string pre_code_i = replace(pre_code, "$array_ixn", s_ixn);
            pre_code_i = replace(pre_code_i, "$i", s_i);
            s_begin ~= pre_code_i;
            string post_code_i = replace(post_code, "$array_ixn", s_ixn);
            post_code_i = replace(post_code_i, "$i", s_i);
            s_end ~= post_code_i;
        }
        return s_begin ~ s_end;
    }

    static if(isPointer!T && isStaticArray!(pointerTarget!T)) {
        alias _dim_list!(pointerTarget!T) _dim;
        /// T, with all nonmutable qualifiers stripped away.
        alias _dim.unqual* unqual;
    }else{
        alias _dim_list!T _dim;
        alias _dim.unqual unqual;
    }
    /// tuple of dimensions of T.
    /// dim_list[0] will be the dimension furthest from the MatrixElementType
    /// i.e. for double[1][2][3], dim_list == (3, 2, 1).
    /// Lists -1 as dimension of dynamic arrays.
    alias _dim.list dim_list;
    /// number of dimensions of this matrix
    enum ndim = dim_list.length;
    /// T is a RectArray if:
    /// * it is any multidimensional static array (or a pointer to)
    /// * it is a 1 dimensional dynamic array
    enum bool isRectArray = staticIndexOf!(-1, dim_list) == -1 || dim_list.length == 1;
    //(1,2,3) -> rectArrayAt == 0 
    //(-1,2,3) -> rectArrayAt == 1 == 3 - 2 == len - max(indexof_rev, 1)
    //(-1,-1,1) -> rectArrayAt == 2 == 3 - 1 == len - max(indexof_rev,1)
    //(-1,-1,-1) -> rectArrayAt == 2 == 3 - 1 == len - max(indexof_rev,1)
    //(2,2,-1) -> rectArrayAt == 2
    enum size_t indexof_rev = staticIndexOf!(-1, Reverse!dim_list);
    /// Highest dimension where it and all subsequent dimensions form a
    /// RectArray.
    enum size_t rectArrayAt = isRectArray ? 0 : dim_list.length - max(indexof_rev, 1);
    template _rect_type(S, size_t i) {
        static if(i == rectArrayAt) {
            alias S _rect_type;
        } else {
            alias _rect_type!(ElementType!S, i+1) _rect_type;
        }
    }
    /// unqualified highest dimension subtype of T forming RectArray
    alias _rect_type!(unqual, 0) RectArrayType;
    /// Pretty string of dimension list for T
    enum string dimstring = tuple2string!(dim_list)();
    /// Matrix element type of T
    /// E.g. immutable(double) for T=immutable(double[4][4])
    alias _dim.elt MatrixElementType;
}

@property PyTypeObject* array_array_Type() {
    static PyTypeObject* m_type;
    if(!m_type) {
        PyObject* array = PyImport_ImportModule("array");
        scope(exit) Py_XDECREF(array);
        m_type = cast(PyTypeObject*) PyObject_GetAttrString(array, "array");
    }
    return m_type;
}

alias python_to_d!(Object) python_to_d_Object;

private
void could_not_convert(T) (PyObject* o, string reason = "", 
        string file = __FILE__, size_t line = __LINE__) {
    // Pull out the name of the type of this Python object, and the
    // name of the D type.
    string py_typename, d_typename;
    PyObject* py_type, py_type_str;
    py_type = PyObject_Type(o);
    if (py_type is null) {
        py_typename = "<unknown>";
    } else {
        py_type_str = PyObject_GetAttrString(py_type, cast(const(char)*) "__name__".ptr);
        Py_DECREF(py_type);
        if (py_type_str is null) {
            py_typename = "<unknown>";
        } else {
            py_typename = python_to_d!string(py_type_str);
            Py_DECREF(py_type_str);
        }
    }
    d_typename = typeid(T).toString();
    string because;
    if(reason != "") because = format(" because: %s", reason);
    throw new PydConversionException(
            format("Couldn't convert Python type '%s' to D type '%s'%s",
                py_typename,
                d_typename,
                because),
            file, line
    );
}

// stuff this down here until we can figure out what to do with it.
// Python-header-file: Modules/arraymodule.c:

struct arraydescr{
    int typecode;
    int itemsize;
    PyObject* function(arrayobject*, Py_ssize_t) getitem;
    int function(arrayobject*, Py_ssize_t, PyObject*) setitem;
}

struct arrayobject {
    mixin PyObject_VAR_HEAD;
    ubyte* ob_item;
    Py_ssize_t allocated;
    arraydescr* ob_descr;
    PyObject* weakreflist; /* List of weak references */
}