diff options
Diffstat (limited to 'numpy/f2py')
26 files changed, 702 insertions, 606 deletions
diff --git a/numpy/f2py/__init__.py b/numpy/f2py/__init__.py index b9b86ba0e..250c4322b 100644 --- a/numpy/f2py/__init__.py +++ b/numpy/f2py/__init__.py @@ -69,6 +69,6 @@ def compile(source, f.close() return status -from numpy.testing.nosetester import _numpy_tester +from numpy.testing import _numpy_tester test = _numpy_tester().test bench = _numpy_tester().bench diff --git a/numpy/f2py/auxfuncs.py b/numpy/f2py/auxfuncs.py index d27b95947..404bdbd2d 100644 --- a/numpy/f2py/auxfuncs.py +++ b/numpy/f2py/auxfuncs.py @@ -552,7 +552,7 @@ class F2PYError(Exception): pass -class throw_error: +class throw_error(object): def __init__(self, mess): self.mess = mess diff --git a/numpy/f2py/capi_maps.py b/numpy/f2py/capi_maps.py index 5b2e6a9b9..64829d30c 100644 --- a/numpy/f2py/capi_maps.py +++ b/numpy/f2py/capi_maps.py @@ -328,7 +328,7 @@ def getarrdims(a, var, verbose=0): ret['size'] = '*'.join(dim) try: ret['size'] = repr(eval(ret['size'])) - except: + except Exception: pass ret['dims'] = ','.join(dim) ret['rank'] = repr(len(dim)) @@ -485,7 +485,7 @@ def getinit(a, var): else: v = eval(v, {}, {}) ret['init.r'], ret['init.i'] = str(v.real), str(v.imag) - except: + except Exception: raise ValueError( 'getinit: expected complex number `(r,i)\' but got `%s\' as initial value of %r.' % (init, a)) if isarray(var): diff --git a/numpy/f2py/cfuncs.py b/numpy/f2py/cfuncs.py index 1632a0d47..6aeeec823 100644 --- a/numpy/f2py/cfuncs.py +++ b/numpy/f2py/cfuncs.py @@ -99,8 +99,8 @@ cppmacros['CFUNCSMESS'] = """\ #ifdef DEBUGCFUNCS #define CFUNCSMESS(mess) fprintf(stderr,\"debug-capi:\"mess); #define CFUNCSMESSPY(mess,obj) CFUNCSMESS(mess) \\ -\tPyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ -\tfprintf(stderr,\"\\n\"); + PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ + fprintf(stderr,\"\\n\"); #else #define CFUNCSMESS(mess) #define CFUNCSMESSPY(mess,obj) @@ -219,18 +219,18 @@ cppmacros['SWAPUNSAFE'] = """\ """ cppmacros['SWAP'] = """\ #define SWAP(a,b,t) {\\ -\tt *c;\\ -\tc = a;\\ -\ta = b;\\ -\tb = c;} + t *c;\\ + c = a;\\ + a = b;\\ + b = c;} """ # cppmacros['ISCONTIGUOUS']='#define ISCONTIGUOUS(m) (PyArray_FLAGS(m) & # NPY_ARRAY_C_CONTIGUOUS)' cppmacros['PRINTPYOBJERR'] = """\ #define PRINTPYOBJERR(obj)\\ -\tfprintf(stderr,\"#modulename#.error is related to \");\\ -\tPyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ -\tfprintf(stderr,\"\\n\"); + fprintf(stderr,\"#modulename#.error is related to \");\\ + PyObject_Print((PyObject *)obj,stderr,Py_PRINT_RAW);\\ + fprintf(stderr,\"\\n\"); """ cppmacros['MINMAX'] = """\ #ifndef max @@ -401,59 +401,59 @@ cppmacros['TRYCOMPLEXPYARRAYTEMPLATE'] = """\ """ # cppmacros['NUMFROMARROBJ']="""\ # define NUMFROMARROBJ(typenum,ctype) \\ -# \tif (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ -# \telse arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ -# \tif (arr) {\\ -# \t\tif (PyArray_TYPE(arr)==NPY_OBJECT) {\\ -# \t\t\tif (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\ -# \t\t\tgoto capi_fail;\\ -# \t\t} else {\\ -# \t\t\t(PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\ -# \t\t}\\ -# \t\tif ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ -# \t\treturn 1;\\ -# \t} +# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ +# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ +# if (arr) {\\ +# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\ +# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\ +# goto capi_fail;\\ +# } else {\\ +# (PyArray_DESCR(arr)->cast[typenum])(PyArray_DATA(arr),1,(char*)v,1,1);\\ +# }\\ +# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ +# return 1;\\ +# } # """ # XXX: Note that CNUMFROMARROBJ is identical with NUMFROMARROBJ # cppmacros['CNUMFROMARROBJ']="""\ # define CNUMFROMARROBJ(typenum,ctype) \\ -# \tif (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ -# \telse arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ -# \tif (arr) {\\ -# \t\tif (PyArray_TYPE(arr)==NPY_OBJECT) {\\ -# \t\t\tif (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\ -# \t\t\tgoto capi_fail;\\ -# \t\t} else {\\ -# \t\t\t(PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\ -# \t\t}\\ -# \t\tif ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ -# \t\treturn 1;\\ -# \t} +# if (PyArray_Check(obj)) arr = (PyArrayObject *)obj;\\ +# else arr = (PyArrayObject *)PyArray_ContiguousFromObject(obj,typenum,0,0);\\ +# if (arr) {\\ +# if (PyArray_TYPE(arr)==NPY_OBJECT) {\\ +# if (!ctype ## _from_pyobj(v,(PyArray_DESCR(arr)->getitem)(PyArray_DATA(arr)),\"\"))\\ +# goto capi_fail;\\ +# } else {\\ +# (PyArray_DESCR(arr)->cast[typenum])((void *)(PyArray_DATA(arr)),1,(void *)(v),1,1);\\ +# }\\ +# if ((PyObject *)arr != obj) { Py_DECREF(arr); }\\ +# return 1;\\ +# } # """ needs['GETSTRFROMPYTUPLE'] = ['STRINGCOPYN', 'PRINTPYOBJERR'] cppmacros['GETSTRFROMPYTUPLE'] = """\ #define GETSTRFROMPYTUPLE(tuple,index,str,len) {\\ -\t\tPyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\ -\t\tif (rv_cb_str == NULL)\\ -\t\t\tgoto capi_fail;\\ -\t\tif (PyString_Check(rv_cb_str)) {\\ -\t\t\tstr[len-1]='\\0';\\ -\t\t\tSTRINGCOPYN((str),PyString_AS_STRING((PyStringObject*)rv_cb_str),(len));\\ -\t\t} else {\\ -\t\t\tPRINTPYOBJERR(rv_cb_str);\\ -\t\t\tPyErr_SetString(#modulename#_error,\"string object expected\");\\ -\t\t\tgoto capi_fail;\\ -\t\t}\\ -\t} + PyObject *rv_cb_str = PyTuple_GetItem((tuple),(index));\\ + if (rv_cb_str == NULL)\\ + goto capi_fail;\\ + if (PyString_Check(rv_cb_str)) {\\ + str[len-1]='\\0';\\ + STRINGCOPYN((str),PyString_AS_STRING((PyStringObject*)rv_cb_str),(len));\\ + } else {\\ + PRINTPYOBJERR(rv_cb_str);\\ + PyErr_SetString(#modulename#_error,\"string object expected\");\\ + goto capi_fail;\\ + }\\ + } """ cppmacros['GETSCALARFROMPYTUPLE'] = """\ #define GETSCALARFROMPYTUPLE(tuple,index,var,ctype,mess) {\\ -\t\tif ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\ -\t\tif (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\ -\t\t\tgoto capi_fail;\\ -\t} + if ((capi_tmp = PyTuple_GetItem((tuple),(index)))==NULL) goto capi_fail;\\ + if (!(ctype ## _from_pyobj((var),capi_tmp,mess)))\\ + goto capi_fail;\\ + } """ cppmacros['FAILNULL'] = """\\ @@ -471,12 +471,12 @@ cppmacros['MEMCOPY'] = """\ """ cppmacros['STRINGMALLOC'] = """\ #define STRINGMALLOC(str,len)\\ -\tif ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\\ -\t\tPyErr_SetString(PyExc_MemoryError, \"out of memory\");\\ -\t\tgoto capi_fail;\\ -\t} else {\\ -\t\t(str)[len] = '\\0';\\ -\t} + if ((str = (string)malloc(sizeof(char)*(len+1))) == NULL) {\\ + PyErr_SetString(PyExc_MemoryError, \"out of memory\");\\ + goto capi_fail;\\ + } else {\\ + (str)[len] = '\\0';\\ + } """ cppmacros['STRINGFREE'] = """\ #define STRINGFREE(str) do {if (!(str == NULL)) free(str);} while (0) @@ -504,39 +504,39 @@ cppmacros['STRINGCOPY'] = """\ """ cppmacros['CHECKGENERIC'] = """\ #define CHECKGENERIC(check,tcheck,name) \\ -\tif (!(check)) {\\ -\t\tPyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ -\t\t/*goto capi_fail;*/\\ -\t} else """ + if (!(check)) {\\ + PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ + /*goto capi_fail;*/\\ + } else """ cppmacros['CHECKARRAY'] = """\ #define CHECKARRAY(check,tcheck,name) \\ -\tif (!(check)) {\\ -\t\tPyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ -\t\t/*goto capi_fail;*/\\ -\t} else """ + if (!(check)) {\\ + PyErr_SetString(#modulename#_error,\"(\"tcheck\") failed for \"name);\\ + /*goto capi_fail;*/\\ + } else """ cppmacros['CHECKSTRING'] = """\ #define CHECKSTRING(check,tcheck,name,show,var)\\ -\tif (!(check)) {\\ -\t\tchar errstring[256];\\ -\t\tsprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\ -\t\tPyErr_SetString(#modulename#_error, errstring);\\ -\t\t/*goto capi_fail;*/\\ -\t} else """ + if (!(check)) {\\ + char errstring[256];\\ + sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, slen(var), var);\\ + PyErr_SetString(#modulename#_error, errstring);\\ + /*goto capi_fail;*/\\ + } else """ cppmacros['CHECKSCALAR'] = """\ #define CHECKSCALAR(check,tcheck,name,show,var)\\ -\tif (!(check)) {\\ -\t\tchar errstring[256];\\ -\t\tsprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\ -\t\tPyErr_SetString(#modulename#_error,errstring);\\ -\t\t/*goto capi_fail;*/\\ -\t} else """ + if (!(check)) {\\ + char errstring[256];\\ + sprintf(errstring, \"%s: \"show, \"(\"tcheck\") failed for \"name, var);\\ + PyErr_SetString(#modulename#_error,errstring);\\ + /*goto capi_fail;*/\\ + } else """ # cppmacros['CHECKDIMS']="""\ # define CHECKDIMS(dims,rank) \\ -# \tfor (int i=0;i<(rank);i++)\\ -# \t\tif (dims[i]<0) {\\ -# \t\t\tfprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\ -# \t\t\tgoto capi_fail;\\ -# \t\t} +# for (int i=0;i<(rank);i++)\\ +# if (dims[i]<0) {\\ +# fprintf(stderr,\"Unspecified array argument requires a complete dimension specification.\\n\");\\ +# goto capi_fail;\\ +# } # """ cppmacros[ 'ARRSIZE'] = '#define ARRSIZE(dims,rank) (_PyArray_multiply_list(dims,rank))' @@ -549,17 +549,17 @@ cppmacros['OLDPYNUM'] = """\ cfuncs['calcarrindex'] = """\ static int calcarrindex(int *i,PyArrayObject *arr) { -\tint k,ii = i[0]; -\tfor (k=1; k < PyArray_NDIM(arr); k++) -\t\tii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */ -\treturn ii; + int k,ii = i[0]; + for (k=1; k < PyArray_NDIM(arr); k++) + ii += (ii*(PyArray_DIM(arr,k) - 1)+i[k]); /* assuming contiguous arr */ + return ii; }""" cfuncs['calcarrindextr'] = """\ static int calcarrindextr(int *i,PyArrayObject *arr) { -\tint k,ii = i[PyArray_NDIM(arr)-1]; -\tfor (k=1; k < PyArray_NDIM(arr); k++) -\t\tii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */ -\treturn ii; + int k,ii = i[PyArray_NDIM(arr)-1]; + for (k=1; k < PyArray_NDIM(arr); k++) + ii += (ii*(PyArray_DIM(arr,PyArray_NDIM(arr)-k-1) - 1)+i[PyArray_NDIM(arr)-k-1]); /* assuming contiguous arr */ + return ii; }""" cfuncs['forcomb'] = """\ static struct { int nd;npy_intp *d;int *i,*i_tr,tr; } forcombcache; @@ -604,543 +604,543 @@ static int *nextforcomb(void) { needs['try_pyarr_from_string'] = ['STRINGCOPYN', 'PRINTPYOBJERR', 'string'] cfuncs['try_pyarr_from_string'] = """\ static int try_pyarr_from_string(PyObject *obj,const string str) { -\tPyArrayObject *arr = NULL; -\tif (PyArray_Check(obj) && (!((arr = (PyArrayObject *)obj) == NULL))) -\t\t{ STRINGCOPYN(PyArray_DATA(arr),str,PyArray_NBYTES(arr)); } -\treturn 1; + PyArrayObject *arr = NULL; + if (PyArray_Check(obj) && (!((arr = (PyArrayObject *)obj) == NULL))) + { STRINGCOPYN(PyArray_DATA(arr),str,PyArray_NBYTES(arr)); } + return 1; capi_fail: -\tPRINTPYOBJERR(obj); -\tPyErr_SetString(#modulename#_error,\"try_pyarr_from_string failed\"); -\treturn 0; + PRINTPYOBJERR(obj); + PyErr_SetString(#modulename#_error,\"try_pyarr_from_string failed\"); + return 0; } """ needs['string_from_pyobj'] = ['string', 'STRINGMALLOC', 'STRINGCOPYN'] cfuncs['string_from_pyobj'] = """\ static int string_from_pyobj(string *str,int *len,const string inistr,PyObject *obj,const char *errmess) { -\tPyArrayObject *arr = NULL; -\tPyObject *tmp = NULL; + PyArrayObject *arr = NULL; + PyObject *tmp = NULL; #ifdef DEBUGCFUNCS fprintf(stderr,\"string_from_pyobj(str='%s',len=%d,inistr='%s',obj=%p)\\n\",(char*)str,*len,(char *)inistr,obj); #endif -\tif (obj == Py_None) { -\t\tif (*len == -1) -\t\t\t*len = strlen(inistr); /* Will this cause problems? */ -\t\tSTRINGMALLOC(*str,*len); -\t\tSTRINGCOPYN(*str,inistr,*len+1); -\t\treturn 1; -\t} -\tif (PyArray_Check(obj)) { -\t\tif ((arr = (PyArrayObject *)obj) == NULL) -\t\t\tgoto capi_fail; -\t\tif (!ISCONTIGUOUS(arr)) { -\t\t\tPyErr_SetString(PyExc_ValueError,\"array object is non-contiguous.\"); -\t\t\tgoto capi_fail; -\t\t} -\t\tif (*len == -1) -\t\t\t*len = (PyArray_ITEMSIZE(arr))*PyArray_SIZE(arr); -\t\tSTRINGMALLOC(*str,*len); -\t\tSTRINGCOPYN(*str,PyArray_DATA(arr),*len+1); -\t\treturn 1; -\t} -\tif (PyString_Check(obj)) { -\t\ttmp = obj; -\t\tPy_INCREF(tmp); -\t} + if (obj == Py_None) { + if (*len == -1) + *len = strlen(inistr); /* Will this cause problems? */ + STRINGMALLOC(*str,*len); + STRINGCOPYN(*str,inistr,*len+1); + return 1; + } + if (PyArray_Check(obj)) { + if ((arr = (PyArrayObject *)obj) == NULL) + goto capi_fail; + if (!ISCONTIGUOUS(arr)) { + PyErr_SetString(PyExc_ValueError,\"array object is non-contiguous.\"); + goto capi_fail; + } + if (*len == -1) + *len = (PyArray_ITEMSIZE(arr))*PyArray_SIZE(arr); + STRINGMALLOC(*str,*len); + STRINGCOPYN(*str,PyArray_DATA(arr),*len+1); + return 1; + } + if (PyString_Check(obj)) { + tmp = obj; + Py_INCREF(tmp); + } #if PY_VERSION_HEX >= 0x03000000 -\telse if (PyUnicode_Check(obj)) { -\t\ttmp = PyUnicode_AsASCIIString(obj); -\t} -\telse { -\t\tPyObject *tmp2; -\t\ttmp2 = PyObject_Str(obj); -\t\tif (tmp2) { -\t\t\ttmp = PyUnicode_AsASCIIString(tmp2); -\t\t\tPy_DECREF(tmp2); -\t\t} -\t\telse { -\t\t\ttmp = NULL; -\t\t} -\t} + else if (PyUnicode_Check(obj)) { + tmp = PyUnicode_AsASCIIString(obj); + } + else { + PyObject *tmp2; + tmp2 = PyObject_Str(obj); + if (tmp2) { + tmp = PyUnicode_AsASCIIString(tmp2); + Py_DECREF(tmp2); + } + else { + tmp = NULL; + } + } #else -\telse { -\t\ttmp = PyObject_Str(obj); -\t} + else { + tmp = PyObject_Str(obj); + } #endif -\tif (tmp == NULL) goto capi_fail; -\tif (*len == -1) -\t\t*len = PyString_GET_SIZE(tmp); -\tSTRINGMALLOC(*str,*len); -\tSTRINGCOPYN(*str,PyString_AS_STRING(tmp),*len+1); -\tPy_DECREF(tmp); -\treturn 1; + if (tmp == NULL) goto capi_fail; + if (*len == -1) + *len = PyString_GET_SIZE(tmp); + STRINGMALLOC(*str,*len); + STRINGCOPYN(*str,PyString_AS_STRING(tmp),*len+1); + Py_DECREF(tmp); + return 1; capi_fail: -\tPy_XDECREF(tmp); -\t{ -\t\tPyObject* err = PyErr_Occurred(); -\t\tif (err==NULL) err = #modulename#_error; -\t\tPyErr_SetString(err,errmess); -\t} -\treturn 0; + Py_XDECREF(tmp); + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) err = #modulename#_error; + PyErr_SetString(err,errmess); + } + return 0; } """ needs['char_from_pyobj'] = ['int_from_pyobj'] cfuncs['char_from_pyobj'] = """\ static int char_from_pyobj(char* v,PyObject *obj,const char *errmess) { -\tint i=0; -\tif (int_from_pyobj(&i,obj,errmess)) { -\t\t*v = (char)i; -\t\treturn 1; -\t} -\treturn 0; + int i=0; + if (int_from_pyobj(&i,obj,errmess)) { + *v = (char)i; + return 1; + } + return 0; } """ needs['signed_char_from_pyobj'] = ['int_from_pyobj', 'signed_char'] cfuncs['signed_char_from_pyobj'] = """\ static int signed_char_from_pyobj(signed_char* v,PyObject *obj,const char *errmess) { -\tint i=0; -\tif (int_from_pyobj(&i,obj,errmess)) { -\t\t*v = (signed_char)i; -\t\treturn 1; -\t} -\treturn 0; + int i=0; + if (int_from_pyobj(&i,obj,errmess)) { + *v = (signed_char)i; + return 1; + } + return 0; } """ needs['short_from_pyobj'] = ['int_from_pyobj'] cfuncs['short_from_pyobj'] = """\ static int short_from_pyobj(short* v,PyObject *obj,const char *errmess) { -\tint i=0; -\tif (int_from_pyobj(&i,obj,errmess)) { -\t\t*v = (short)i; -\t\treturn 1; -\t} -\treturn 0; + int i=0; + if (int_from_pyobj(&i,obj,errmess)) { + *v = (short)i; + return 1; + } + return 0; } """ cfuncs['int_from_pyobj'] = """\ static int int_from_pyobj(int* v,PyObject *obj,const char *errmess) { -\tPyObject* tmp = NULL; -\tif (PyInt_Check(obj)) { -\t\t*v = (int)PyInt_AS_LONG(obj); -\t\treturn 1; -\t} -\ttmp = PyNumber_Int(obj); -\tif (tmp) { -\t\t*v = PyInt_AS_LONG(tmp); -\t\tPy_DECREF(tmp); -\t\treturn 1; -\t} -\tif (PyComplex_Check(obj)) -\t\ttmp = PyObject_GetAttrString(obj,\"real\"); -\telse if (PyString_Check(obj) || PyUnicode_Check(obj)) -\t\t/*pass*/; -\telse if (PySequence_Check(obj)) -\t\ttmp = PySequence_GetItem(obj,0); -\tif (tmp) { -\t\tPyErr_Clear(); -\t\tif (int_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} -\t\tPy_DECREF(tmp); -\t} -\t{ -\t\tPyObject* err = PyErr_Occurred(); -\t\tif (err==NULL) err = #modulename#_error; -\t\tPyErr_SetString(err,errmess); -\t} -\treturn 0; + PyObject* tmp = NULL; + if (PyInt_Check(obj)) { + *v = (int)PyInt_AS_LONG(obj); + return 1; + } + tmp = PyNumber_Int(obj); + if (tmp) { + *v = PyInt_AS_LONG(tmp); + Py_DECREF(tmp); + return 1; + } + if (PyComplex_Check(obj)) + tmp = PyObject_GetAttrString(obj,\"real\"); + else if (PyString_Check(obj) || PyUnicode_Check(obj)) + /*pass*/; + else if (PySequence_Check(obj)) + tmp = PySequence_GetItem(obj,0); + if (tmp) { + PyErr_Clear(); + if (int_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) err = #modulename#_error; + PyErr_SetString(err,errmess); + } + return 0; } """ cfuncs['long_from_pyobj'] = """\ static int long_from_pyobj(long* v,PyObject *obj,const char *errmess) { -\tPyObject* tmp = NULL; -\tif (PyInt_Check(obj)) { -\t\t*v = PyInt_AS_LONG(obj); -\t\treturn 1; -\t} -\ttmp = PyNumber_Int(obj); -\tif (tmp) { -\t\t*v = PyInt_AS_LONG(tmp); -\t\tPy_DECREF(tmp); -\t\treturn 1; -\t} -\tif (PyComplex_Check(obj)) -\t\ttmp = PyObject_GetAttrString(obj,\"real\"); -\telse if (PyString_Check(obj) || PyUnicode_Check(obj)) -\t\t/*pass*/; -\telse if (PySequence_Check(obj)) -\t\ttmp = PySequence_GetItem(obj,0); -\tif (tmp) { -\t\tPyErr_Clear(); -\t\tif (long_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} -\t\tPy_DECREF(tmp); -\t} -\t{ -\t\tPyObject* err = PyErr_Occurred(); -\t\tif (err==NULL) err = #modulename#_error; -\t\tPyErr_SetString(err,errmess); -\t} -\treturn 0; + PyObject* tmp = NULL; + if (PyInt_Check(obj)) { + *v = PyInt_AS_LONG(obj); + return 1; + } + tmp = PyNumber_Int(obj); + if (tmp) { + *v = PyInt_AS_LONG(tmp); + Py_DECREF(tmp); + return 1; + } + if (PyComplex_Check(obj)) + tmp = PyObject_GetAttrString(obj,\"real\"); + else if (PyString_Check(obj) || PyUnicode_Check(obj)) + /*pass*/; + else if (PySequence_Check(obj)) + tmp = PySequence_GetItem(obj,0); + if (tmp) { + PyErr_Clear(); + if (long_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) err = #modulename#_error; + PyErr_SetString(err,errmess); + } + return 0; } """ needs['long_long_from_pyobj'] = ['long_long'] cfuncs['long_long_from_pyobj'] = """\ static int long_long_from_pyobj(long_long* v,PyObject *obj,const char *errmess) { -\tPyObject* tmp = NULL; -\tif (PyLong_Check(obj)) { -\t\t*v = PyLong_AsLongLong(obj); -\t\treturn (!PyErr_Occurred()); -\t} -\tif (PyInt_Check(obj)) { -\t\t*v = (long_long)PyInt_AS_LONG(obj); -\t\treturn 1; -\t} -\ttmp = PyNumber_Long(obj); -\tif (tmp) { -\t\t*v = PyLong_AsLongLong(tmp); -\t\tPy_DECREF(tmp); -\t\treturn (!PyErr_Occurred()); -\t} -\tif (PyComplex_Check(obj)) -\t\ttmp = PyObject_GetAttrString(obj,\"real\"); -\telse if (PyString_Check(obj) || PyUnicode_Check(obj)) -\t\t/*pass*/; -\telse if (PySequence_Check(obj)) -\t\ttmp = PySequence_GetItem(obj,0); -\tif (tmp) { -\t\tPyErr_Clear(); -\t\tif (long_long_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} -\t\tPy_DECREF(tmp); -\t} -\t{ -\t\tPyObject* err = PyErr_Occurred(); -\t\tif (err==NULL) err = #modulename#_error; -\t\tPyErr_SetString(err,errmess); -\t} -\treturn 0; + PyObject* tmp = NULL; + if (PyLong_Check(obj)) { + *v = PyLong_AsLongLong(obj); + return (!PyErr_Occurred()); + } + if (PyInt_Check(obj)) { + *v = (long_long)PyInt_AS_LONG(obj); + return 1; + } + tmp = PyNumber_Long(obj); + if (tmp) { + *v = PyLong_AsLongLong(tmp); + Py_DECREF(tmp); + return (!PyErr_Occurred()); + } + if (PyComplex_Check(obj)) + tmp = PyObject_GetAttrString(obj,\"real\"); + else if (PyString_Check(obj) || PyUnicode_Check(obj)) + /*pass*/; + else if (PySequence_Check(obj)) + tmp = PySequence_GetItem(obj,0); + if (tmp) { + PyErr_Clear(); + if (long_long_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) err = #modulename#_error; + PyErr_SetString(err,errmess); + } + return 0; } """ needs['long_double_from_pyobj'] = ['double_from_pyobj', 'long_double'] cfuncs['long_double_from_pyobj'] = """\ static int long_double_from_pyobj(long_double* v,PyObject *obj,const char *errmess) { -\tdouble d=0; -\tif (PyArray_CheckScalar(obj)){ -\t\tif PyArray_IsScalar(obj, LongDouble) { -\t\t\tPyArray_ScalarAsCtype(obj, v); -\t\t\treturn 1; -\t\t} -\t\telse if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_LONGDOUBLE) { -\t\t\t(*v) = *((npy_longdouble *)PyArray_DATA(obj)); -\t\t\treturn 1; -\t\t} -\t} -\tif (double_from_pyobj(&d,obj,errmess)) { -\t\t*v = (long_double)d; -\t\treturn 1; -\t} -\treturn 0; + double d=0; + if (PyArray_CheckScalar(obj)){ + if PyArray_IsScalar(obj, LongDouble) { + PyArray_ScalarAsCtype(obj, v); + return 1; + } + else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_LONGDOUBLE) { + (*v) = *((npy_longdouble *)PyArray_DATA(obj)); + return 1; + } + } + if (double_from_pyobj(&d,obj,errmess)) { + *v = (long_double)d; + return 1; + } + return 0; } """ cfuncs['double_from_pyobj'] = """\ static int double_from_pyobj(double* v,PyObject *obj,const char *errmess) { -\tPyObject* tmp = NULL; -\tif (PyFloat_Check(obj)) { + PyObject* tmp = NULL; + if (PyFloat_Check(obj)) { #ifdef __sgi -\t\t*v = PyFloat_AsDouble(obj); + *v = PyFloat_AsDouble(obj); #else -\t\t*v = PyFloat_AS_DOUBLE(obj); + *v = PyFloat_AS_DOUBLE(obj); #endif -\t\treturn 1; -\t} -\ttmp = PyNumber_Float(obj); -\tif (tmp) { + return 1; + } + tmp = PyNumber_Float(obj); + if (tmp) { #ifdef __sgi -\t\t*v = PyFloat_AsDouble(tmp); + *v = PyFloat_AsDouble(tmp); #else -\t\t*v = PyFloat_AS_DOUBLE(tmp); + *v = PyFloat_AS_DOUBLE(tmp); #endif -\t\tPy_DECREF(tmp); -\t\treturn 1; -\t} -\tif (PyComplex_Check(obj)) -\t\ttmp = PyObject_GetAttrString(obj,\"real\"); -\telse if (PyString_Check(obj) || PyUnicode_Check(obj)) -\t\t/*pass*/; -\telse if (PySequence_Check(obj)) -\t\ttmp = PySequence_GetItem(obj,0); -\tif (tmp) { -\t\tPyErr_Clear(); -\t\tif (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} -\t\tPy_DECREF(tmp); -\t} -\t{ -\t\tPyObject* err = PyErr_Occurred(); -\t\tif (err==NULL) err = #modulename#_error; -\t\tPyErr_SetString(err,errmess); -\t} -\treturn 0; + Py_DECREF(tmp); + return 1; + } + if (PyComplex_Check(obj)) + tmp = PyObject_GetAttrString(obj,\"real\"); + else if (PyString_Check(obj) || PyUnicode_Check(obj)) + /*pass*/; + else if (PySequence_Check(obj)) + tmp = PySequence_GetItem(obj,0); + if (tmp) { + PyErr_Clear(); + if (double_from_pyobj(v,tmp,errmess)) {Py_DECREF(tmp); return 1;} + Py_DECREF(tmp); + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) err = #modulename#_error; + PyErr_SetString(err,errmess); + } + return 0; } """ needs['float_from_pyobj'] = ['double_from_pyobj'] cfuncs['float_from_pyobj'] = """\ static int float_from_pyobj(float* v,PyObject *obj,const char *errmess) { -\tdouble d=0.0; -\tif (double_from_pyobj(&d,obj,errmess)) { -\t\t*v = (float)d; -\t\treturn 1; -\t} -\treturn 0; + double d=0.0; + if (double_from_pyobj(&d,obj,errmess)) { + *v = (float)d; + return 1; + } + return 0; } """ needs['complex_long_double_from_pyobj'] = ['complex_long_double', 'long_double', 'complex_double_from_pyobj'] cfuncs['complex_long_double_from_pyobj'] = """\ static int complex_long_double_from_pyobj(complex_long_double* v,PyObject *obj,const char *errmess) { -\tcomplex_double cd={0.0,0.0}; -\tif (PyArray_CheckScalar(obj)){ -\t\tif PyArray_IsScalar(obj, CLongDouble) { -\t\t\tPyArray_ScalarAsCtype(obj, v); -\t\t\treturn 1; -\t\t} -\t\telse if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) { -\t\t\t(*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real; -\t\t\t(*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag; -\t\t\treturn 1; -\t\t} -\t} -\tif (complex_double_from_pyobj(&cd,obj,errmess)) { -\t\t(*v).r = (long_double)cd.r; -\t\t(*v).i = (long_double)cd.i; -\t\treturn 1; -\t} -\treturn 0; + complex_double cd={0.0,0.0}; + if (PyArray_CheckScalar(obj)){ + if PyArray_IsScalar(obj, CLongDouble) { + PyArray_ScalarAsCtype(obj, v); + return 1; + } + else if (PyArray_Check(obj) && PyArray_TYPE(obj)==NPY_CLONGDOUBLE) { + (*v).r = ((npy_clongdouble *)PyArray_DATA(obj))->real; + (*v).i = ((npy_clongdouble *)PyArray_DATA(obj))->imag; + return 1; + } + } + if (complex_double_from_pyobj(&cd,obj,errmess)) { + (*v).r = (long_double)cd.r; + (*v).i = (long_double)cd.i; + return 1; + } + return 0; } """ needs['complex_double_from_pyobj'] = ['complex_double'] cfuncs['complex_double_from_pyobj'] = """\ static int complex_double_from_pyobj(complex_double* v,PyObject *obj,const char *errmess) { -\tPy_complex c; -\tif (PyComplex_Check(obj)) { -\t\tc=PyComplex_AsCComplex(obj); -\t\t(*v).r=c.real, (*v).i=c.imag; -\t\treturn 1; -\t} -\tif (PyArray_IsScalar(obj, ComplexFloating)) { -\t\tif (PyArray_IsScalar(obj, CFloat)) { -\t\t\tnpy_cfloat new; -\t\t\tPyArray_ScalarAsCtype(obj, &new); -\t\t\t(*v).r = (double)new.real; -\t\t\t(*v).i = (double)new.imag; -\t\t} -\t\telse if (PyArray_IsScalar(obj, CLongDouble)) { -\t\t\tnpy_clongdouble new; -\t\t\tPyArray_ScalarAsCtype(obj, &new); -\t\t\t(*v).r = (double)new.real; -\t\t\t(*v).i = (double)new.imag; -\t\t} -\t\telse { /* if (PyArray_IsScalar(obj, CDouble)) */ -\t\t\tPyArray_ScalarAsCtype(obj, v); -\t\t} -\t\treturn 1; -\t} -\tif (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */ -\t\tPyObject *arr; -\t\tif (PyArray_Check(obj)) { -\t\t\tarr = PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE); -\t\t} -\t\telse { -\t\t\tarr = PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE)); -\t\t} -\t\tif (arr==NULL) return 0; -\t\t(*v).r = ((npy_cdouble *)PyArray_DATA(arr))->real; -\t\t(*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag; -\t\treturn 1; -\t} -\t/* Python does not provide PyNumber_Complex function :-( */ -\t(*v).i=0.0; -\tif (PyFloat_Check(obj)) { + Py_complex c; + if (PyComplex_Check(obj)) { + c=PyComplex_AsCComplex(obj); + (*v).r=c.real, (*v).i=c.imag; + return 1; + } + if (PyArray_IsScalar(obj, ComplexFloating)) { + if (PyArray_IsScalar(obj, CFloat)) { + npy_cfloat new; + PyArray_ScalarAsCtype(obj, &new); + (*v).r = (double)new.real; + (*v).i = (double)new.imag; + } + else if (PyArray_IsScalar(obj, CLongDouble)) { + npy_clongdouble new; + PyArray_ScalarAsCtype(obj, &new); + (*v).r = (double)new.real; + (*v).i = (double)new.imag; + } + else { /* if (PyArray_IsScalar(obj, CDouble)) */ + PyArray_ScalarAsCtype(obj, v); + } + return 1; + } + if (PyArray_CheckScalar(obj)) { /* 0-dim array or still array scalar */ + PyObject *arr; + if (PyArray_Check(obj)) { + arr = PyArray_Cast((PyArrayObject *)obj, NPY_CDOUBLE); + } + else { + arr = PyArray_FromScalar(obj, PyArray_DescrFromType(NPY_CDOUBLE)); + } + if (arr==NULL) return 0; + (*v).r = ((npy_cdouble *)PyArray_DATA(arr))->real; + (*v).i = ((npy_cdouble *)PyArray_DATA(arr))->imag; + return 1; + } + /* Python does not provide PyNumber_Complex function :-( */ + (*v).i=0.0; + if (PyFloat_Check(obj)) { #ifdef __sgi -\t\t(*v).r = PyFloat_AsDouble(obj); + (*v).r = PyFloat_AsDouble(obj); #else -\t\t(*v).r = PyFloat_AS_DOUBLE(obj); + (*v).r = PyFloat_AS_DOUBLE(obj); #endif -\t\treturn 1; -\t} -\tif (PyInt_Check(obj)) { -\t\t(*v).r = (double)PyInt_AS_LONG(obj); -\t\treturn 1; -\t} -\tif (PyLong_Check(obj)) { -\t\t(*v).r = PyLong_AsDouble(obj); -\t\treturn (!PyErr_Occurred()); -\t} -\tif (PySequence_Check(obj) && !(PyString_Check(obj) || PyUnicode_Check(obj))) { -\t\tPyObject *tmp = PySequence_GetItem(obj,0); -\t\tif (tmp) { -\t\t\tif (complex_double_from_pyobj(v,tmp,errmess)) { -\t\t\t\tPy_DECREF(tmp); -\t\t\t\treturn 1; -\t\t\t} -\t\t\tPy_DECREF(tmp); -\t\t} -\t} -\t{ -\t\tPyObject* err = PyErr_Occurred(); -\t\tif (err==NULL) -\t\t\terr = PyExc_TypeError; -\t\tPyErr_SetString(err,errmess); -\t} -\treturn 0; + return 1; + } + if (PyInt_Check(obj)) { + (*v).r = (double)PyInt_AS_LONG(obj); + return 1; + } + if (PyLong_Check(obj)) { + (*v).r = PyLong_AsDouble(obj); + return (!PyErr_Occurred()); + } + if (PySequence_Check(obj) && !(PyString_Check(obj) || PyUnicode_Check(obj))) { + PyObject *tmp = PySequence_GetItem(obj,0); + if (tmp) { + if (complex_double_from_pyobj(v,tmp,errmess)) { + Py_DECREF(tmp); + return 1; + } + Py_DECREF(tmp); + } + } + { + PyObject* err = PyErr_Occurred(); + if (err==NULL) + err = PyExc_TypeError; + PyErr_SetString(err,errmess); + } + return 0; } """ needs['complex_float_from_pyobj'] = [ 'complex_float', 'complex_double_from_pyobj'] cfuncs['complex_float_from_pyobj'] = """\ static int complex_float_from_pyobj(complex_float* v,PyObject *obj,const char *errmess) { -\tcomplex_double cd={0.0,0.0}; -\tif (complex_double_from_pyobj(&cd,obj,errmess)) { -\t\t(*v).r = (float)cd.r; -\t\t(*v).i = (float)cd.i; -\t\treturn 1; -\t} -\treturn 0; + complex_double cd={0.0,0.0}; + if (complex_double_from_pyobj(&cd,obj,errmess)) { + (*v).r = (float)cd.r; + (*v).i = (float)cd.i; + return 1; + } + return 0; } """ needs['try_pyarr_from_char'] = ['pyobj_from_char1', 'TRYPYARRAYTEMPLATE'] cfuncs[ - 'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n\tTRYPYARRAYTEMPLATE(char,\'c\');\n}\n' + 'try_pyarr_from_char'] = 'static int try_pyarr_from_char(PyObject* obj,char* v) {\n TRYPYARRAYTEMPLATE(char,\'c\');\n}\n' needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'unsigned_char'] cfuncs[ - 'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n\tTRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n' + 'try_pyarr_from_unsigned_char'] = 'static int try_pyarr_from_unsigned_char(PyObject* obj,unsigned_char* v) {\n TRYPYARRAYTEMPLATE(unsigned_char,\'b\');\n}\n' needs['try_pyarr_from_signed_char'] = ['TRYPYARRAYTEMPLATE', 'signed_char'] cfuncs[ - 'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n\tTRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n' + 'try_pyarr_from_signed_char'] = 'static int try_pyarr_from_signed_char(PyObject* obj,signed_char* v) {\n TRYPYARRAYTEMPLATE(signed_char,\'1\');\n}\n' needs['try_pyarr_from_short'] = ['pyobj_from_short1', 'TRYPYARRAYTEMPLATE'] cfuncs[ - 'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n\tTRYPYARRAYTEMPLATE(short,\'s\');\n}\n' + 'try_pyarr_from_short'] = 'static int try_pyarr_from_short(PyObject* obj,short* v) {\n TRYPYARRAYTEMPLATE(short,\'s\');\n}\n' needs['try_pyarr_from_int'] = ['pyobj_from_int1', 'TRYPYARRAYTEMPLATE'] cfuncs[ - 'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n\tTRYPYARRAYTEMPLATE(int,\'i\');\n}\n' + 'try_pyarr_from_int'] = 'static int try_pyarr_from_int(PyObject* obj,int* v) {\n TRYPYARRAYTEMPLATE(int,\'i\');\n}\n' needs['try_pyarr_from_long'] = ['pyobj_from_long1', 'TRYPYARRAYTEMPLATE'] cfuncs[ - 'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n\tTRYPYARRAYTEMPLATE(long,\'l\');\n}\n' + 'try_pyarr_from_long'] = 'static int try_pyarr_from_long(PyObject* obj,long* v) {\n TRYPYARRAYTEMPLATE(long,\'l\');\n}\n' needs['try_pyarr_from_long_long'] = [ 'pyobj_from_long_long1', 'TRYPYARRAYTEMPLATE', 'long_long'] cfuncs[ - 'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n\tTRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n' + 'try_pyarr_from_long_long'] = 'static int try_pyarr_from_long_long(PyObject* obj,long_long* v) {\n TRYPYARRAYTEMPLATE(long_long,\'L\');\n}\n' needs['try_pyarr_from_float'] = ['pyobj_from_float1', 'TRYPYARRAYTEMPLATE'] cfuncs[ - 'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n\tTRYPYARRAYTEMPLATE(float,\'f\');\n}\n' + 'try_pyarr_from_float'] = 'static int try_pyarr_from_float(PyObject* obj,float* v) {\n TRYPYARRAYTEMPLATE(float,\'f\');\n}\n' needs['try_pyarr_from_double'] = ['pyobj_from_double1', 'TRYPYARRAYTEMPLATE'] cfuncs[ - 'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n\tTRYPYARRAYTEMPLATE(double,\'d\');\n}\n' + 'try_pyarr_from_double'] = 'static int try_pyarr_from_double(PyObject* obj,double* v) {\n TRYPYARRAYTEMPLATE(double,\'d\');\n}\n' needs['try_pyarr_from_complex_float'] = [ 'pyobj_from_complex_float1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_float'] cfuncs[ - 'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n\tTRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n' + 'try_pyarr_from_complex_float'] = 'static int try_pyarr_from_complex_float(PyObject* obj,complex_float* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(float,\'F\');\n}\n' needs['try_pyarr_from_complex_double'] = [ 'pyobj_from_complex_double1', 'TRYCOMPLEXPYARRAYTEMPLATE', 'complex_double'] cfuncs[ - 'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n\tTRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n' + 'try_pyarr_from_complex_double'] = 'static int try_pyarr_from_complex_double(PyObject* obj,complex_double* v) {\n TRYCOMPLEXPYARRAYTEMPLATE(double,\'D\');\n}\n' needs['create_cb_arglist'] = ['CFUNCSMESS', 'PRINTPYOBJERR', 'MINMAX'] cfuncs['create_cb_arglist'] = """\ static int create_cb_arglist(PyObject* fun,PyTupleObject* xa,const int maxnofargs,const int nofoptargs,int *nofargs,PyTupleObject **args,const char *errmess) { -\tPyObject *tmp = NULL; -\tPyObject *tmp_fun = NULL; -\tint tot,opt,ext,siz,i,di=0; -\tCFUNCSMESS(\"create_cb_arglist\\n\"); -\ttot=opt=ext=siz=0; -\t/* Get the total number of arguments */ -\tif (PyFunction_Check(fun)) -\t\ttmp_fun = fun; -\telse { -\t\tdi = 1; -\t\tif (PyObject_HasAttrString(fun,\"im_func\")) { -\t\t\ttmp_fun = PyObject_GetAttrString(fun,\"im_func\"); -\t\t} -\t\telse if (PyObject_HasAttrString(fun,\"__call__\")) { -\t\t\ttmp = PyObject_GetAttrString(fun,\"__call__\"); -\t\t\tif (PyObject_HasAttrString(tmp,\"im_func\")) -\t\t\t\ttmp_fun = PyObject_GetAttrString(tmp,\"im_func\"); -\t\t\telse { -\t\t\t\ttmp_fun = fun; /* built-in function */ -\t\t\t\ttot = maxnofargs; -\t\t\t\tif (xa != NULL) -\t\t\t\t\ttot += PyTuple_Size((PyObject *)xa); -\t\t\t} -\t\t\tPy_XDECREF(tmp); -\t\t} -\t\telse if (PyFortran_Check(fun) || PyFortran_Check1(fun)) { -\t\t\ttot = maxnofargs; -\t\t\tif (xa != NULL) -\t\t\t\ttot += PyTuple_Size((PyObject *)xa); -\t\t\ttmp_fun = fun; -\t\t} -\t\telse if (F2PyCapsule_Check(fun)) { -\t\t\ttot = maxnofargs; -\t\t\tif (xa != NULL) -\t\t\t\text = PyTuple_Size((PyObject *)xa); -\t\t\tif(ext>0) { -\t\t\t\tfprintf(stderr,\"extra arguments tuple cannot be used with CObject call-back\\n\"); -\t\t\t\tgoto capi_fail; -\t\t\t} -\t\t\ttmp_fun = fun; -\t\t} -\t} + PyObject *tmp = NULL; + PyObject *tmp_fun = NULL; + int tot,opt,ext,siz,i,di=0; + CFUNCSMESS(\"create_cb_arglist\\n\"); + tot=opt=ext=siz=0; + /* Get the total number of arguments */ + if (PyFunction_Check(fun)) + tmp_fun = fun; + else { + di = 1; + if (PyObject_HasAttrString(fun,\"im_func\")) { + tmp_fun = PyObject_GetAttrString(fun,\"im_func\"); + } + else if (PyObject_HasAttrString(fun,\"__call__\")) { + tmp = PyObject_GetAttrString(fun,\"__call__\"); + if (PyObject_HasAttrString(tmp,\"im_func\")) + tmp_fun = PyObject_GetAttrString(tmp,\"im_func\"); + else { + tmp_fun = fun; /* built-in function */ + tot = maxnofargs; + if (xa != NULL) + tot += PyTuple_Size((PyObject *)xa); + } + Py_XDECREF(tmp); + } + else if (PyFortran_Check(fun) || PyFortran_Check1(fun)) { + tot = maxnofargs; + if (xa != NULL) + tot += PyTuple_Size((PyObject *)xa); + tmp_fun = fun; + } + else if (F2PyCapsule_Check(fun)) { + tot = maxnofargs; + if (xa != NULL) + ext = PyTuple_Size((PyObject *)xa); + if(ext>0) { + fprintf(stderr,\"extra arguments tuple cannot be used with CObject call-back\\n\"); + goto capi_fail; + } + tmp_fun = fun; + } + } if (tmp_fun==NULL) { fprintf(stderr,\"Call-back argument must be function|instance|instance.__call__|f2py-function but got %s.\\n\",(fun==NULL?\"NULL\":Py_TYPE(fun)->tp_name)); goto capi_fail; } #if PY_VERSION_HEX >= 0x03000000 -\tif (PyObject_HasAttrString(tmp_fun,\"__code__\")) { -\t\tif (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) + if (PyObject_HasAttrString(tmp_fun,\"__code__\")) { + if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"__code__\"),\"co_argcount\")) #else -\tif (PyObject_HasAttrString(tmp_fun,\"func_code\")) { -\t\tif (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"func_code\"),\"co_argcount\")) + if (PyObject_HasAttrString(tmp_fun,\"func_code\")) { + if (PyObject_HasAttrString(tmp = PyObject_GetAttrString(tmp_fun,\"func_code\"),\"co_argcount\")) #endif -\t\t\ttot = PyInt_AsLong(PyObject_GetAttrString(tmp,\"co_argcount\")) - di; -\t\tPy_XDECREF(tmp); -\t} -\t/* Get the number of optional arguments */ + tot = PyInt_AsLong(PyObject_GetAttrString(tmp,\"co_argcount\")) - di; + Py_XDECREF(tmp); + } + /* Get the number of optional arguments */ #if PY_VERSION_HEX >= 0x03000000 -\tif (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) { -\t\tif (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\"))) + if (PyObject_HasAttrString(tmp_fun,\"__defaults__\")) { + if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"__defaults__\"))) #else -\tif (PyObject_HasAttrString(tmp_fun,\"func_defaults\")) { -\t\tif (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"func_defaults\"))) + if (PyObject_HasAttrString(tmp_fun,\"func_defaults\")) { + if (PyTuple_Check(tmp = PyObject_GetAttrString(tmp_fun,\"func_defaults\"))) #endif -\t\t\topt = PyTuple_Size(tmp); -\t\tPy_XDECREF(tmp); -\t} -\t/* Get the number of extra arguments */ -\tif (xa != NULL) -\t\text = PyTuple_Size((PyObject *)xa); -\t/* Calculate the size of call-backs argument list */ -\tsiz = MIN(maxnofargs+ext,tot); -\t*nofargs = MAX(0,siz-ext); + opt = PyTuple_Size(tmp); + Py_XDECREF(tmp); + } + /* Get the number of extra arguments */ + if (xa != NULL) + ext = PyTuple_Size((PyObject *)xa); + /* Calculate the size of call-backs argument list */ + siz = MIN(maxnofargs+ext,tot); + *nofargs = MAX(0,siz-ext); #ifdef DEBUGCFUNCS -\tfprintf(stderr,\"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),tot,opt,ext,siz,nofargs=%d(-%d),%d,%d,%d,%d,%d\\n\",maxnofargs,nofoptargs,tot,opt,ext,siz,*nofargs); + fprintf(stderr,\"debug-capi:create_cb_arglist:maxnofargs(-nofoptargs),tot,opt,ext,siz,nofargs=%d(-%d),%d,%d,%d,%d,%d\\n\",maxnofargs,nofoptargs,tot,opt,ext,siz,*nofargs); #endif -\tif (siz<tot-opt) { -\t\tfprintf(stderr,\"create_cb_arglist: Failed to build argument list (siz) with enough arguments (tot-opt) required by user-supplied function (siz,tot,opt=%d,%d,%d).\\n\",siz,tot,opt); -\t\tgoto capi_fail; -\t} -\t/* Initialize argument list */ -\t*args = (PyTupleObject *)PyTuple_New(siz); -\tfor (i=0;i<*nofargs;i++) { -\t\tPy_INCREF(Py_None); -\t\tPyTuple_SET_ITEM((PyObject *)(*args),i,Py_None); -\t} -\tif (xa != NULL) -\t\tfor (i=(*nofargs);i<siz;i++) { -\t\t\ttmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs)); -\t\t\tPy_INCREF(tmp); -\t\t\tPyTuple_SET_ITEM(*args,i,tmp); -\t\t} -\tCFUNCSMESS(\"create_cb_arglist-end\\n\"); -\treturn 1; + if (siz<tot-opt) { + fprintf(stderr,\"create_cb_arglist: Failed to build argument list (siz) with enough arguments (tot-opt) required by user-supplied function (siz,tot,opt=%d,%d,%d).\\n\",siz,tot,opt); + goto capi_fail; + } + /* Initialize argument list */ + *args = (PyTupleObject *)PyTuple_New(siz); + for (i=0;i<*nofargs;i++) { + Py_INCREF(Py_None); + PyTuple_SET_ITEM((PyObject *)(*args),i,Py_None); + } + if (xa != NULL) + for (i=(*nofargs);i<siz;i++) { + tmp = PyTuple_GetItem((PyObject *)xa,i-(*nofargs)); + Py_INCREF(tmp); + PyTuple_SET_ITEM(*args,i,tmp); + } + CFUNCSMESS(\"create_cb_arglist-end\\n\"); + return 1; capi_fail: -\tif ((PyErr_Occurred())==NULL) -\t\tPyErr_SetString(#modulename#_error,errmess); -\treturn 0; + if ((PyErr_Occurred())==NULL) + PyErr_SetString(#modulename#_error,errmess); + return 0; } """ diff --git a/numpy/f2py/crackfortran.py b/numpy/f2py/crackfortran.py index 24f9434c4..677f4bae3 100755 --- a/numpy/f2py/crackfortran.py +++ b/numpy/f2py/crackfortran.py @@ -308,22 +308,21 @@ def is_free_format(file): # f90 allows both fixed and free format, assuming fixed unless # signs of free format are detected. result = 0 - f = open(file, 'r') - line = f.readline() - n = 15 # the number of non-comment lines to scan for hints - if _has_f_header(line): - n = 0 - elif _has_f90_header(line): - n = 0 - result = 1 - while n > 0 and line: - if line[0] != '!' and line.strip(): - n -= 1 - if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&': - result = 1 - break + with open(file, 'r') as f: line = f.readline() - f.close() + n = 15 # the number of non-comment lines to scan for hints + if _has_f_header(line): + n = 0 + elif _has_f90_header(line): + n = 0 + result = 1 + while n > 0 and line: + if line[0] != '!' and line.strip(): + n -= 1 + if (line[0] != '\t' and _free_f90_start(line[:5])) or line[-2:-1] == '&': + result = 1 + break + line = f.readline() return result @@ -1036,13 +1035,13 @@ def analyzeline(m, case, line): try: del groupcache[groupcounter]['vars'][name][ groupcache[groupcounter]['vars'][name]['attrspec'].index('external')] - except: + except Exception: pass if block in ['function', 'subroutine']: # set global attributes try: groupcache[groupcounter]['vars'][name] = appenddecl( groupcache[groupcounter]['vars'][name], groupcache[groupcounter - 2]['vars']['']) - except: + except Exception: pass if case == 'callfun': # return type if result and result in groupcache[groupcounter]['vars']: @@ -1052,7 +1051,7 @@ def analyzeline(m, case, line): # if groupcounter>1: # name is interfaced try: groupcache[groupcounter - 2]['interfaced'].append(name) - except: + except Exception: pass if block == 'function': t = typespattern[0].match(m.group('before') + ' ' + name) @@ -1174,7 +1173,7 @@ def analyzeline(m, case, line): for e in markoutercomma(ll).split('@,@'): try: k, initexpr = [x.strip() for x in e.split('=')] - except: + except Exception: outmess( 'analyzeline: could not extract name,expr in parameter statement "%s" of "%s"\n' % (e, ll)) continue @@ -1251,7 +1250,7 @@ def analyzeline(m, case, line): if '-' in r: try: begc, endc = [x.strip() for x in r.split('-')] - except: + except Exception: outmess( 'analyzeline: expected "<char>-<char>" instead of "%s" in range list of implicit statement\n' % r) continue @@ -1790,7 +1789,7 @@ def setmesstext(block): try: filepositiontext = 'In: %s:%s\n' % (block['from'], block['name']) - except: + except Exception: pass @@ -2013,7 +2012,7 @@ def analyzecommon(block): if m.group('dims'): dims = [x.strip() for x in markoutercomma(m.group('dims')).split('@,@')] - n = m.group('name').strip() + n = rmbadname1(m.group('name').strip()) if n in block['vars']: if 'attrspec' in block['vars'][n]: block['vars'][n]['attrspec'].append( @@ -2108,7 +2107,7 @@ def getlincoef(e, xset): # e = a*x+b ; x in xset try: c = int(myeval(e, {}, {})) return 0, c, None - except: + except Exception: pass if getlincoef_re_1.match(e): return 1, 0, e @@ -2150,7 +2149,7 @@ def getlincoef(e, xset): # e = a*x+b ; x in xset c2 = myeval(ee, {}, {}) if (a * 0.5 + b == c and a * 1.5 + b == c2): return a, b, x - except: + except Exception: pass break return None, None, None @@ -2162,11 +2161,11 @@ def getarrlen(dl, args, star='*'): edl = [] try: edl.append(myeval(dl[0], {}, {})) - except: + except Exception: edl.append(dl[0]) try: edl.append(myeval(dl[1], {}, {})) - except: + except Exception: edl.append(dl[1]) if isinstance(edl[0], int): p1 = 1 - edl[0] @@ -2186,7 +2185,7 @@ def getarrlen(dl, args, star='*'): d = '%s-(%s)+1' % (dl[1], dl[0]) try: return repr(myeval(d, {}, {})), None, None - except: + except Exception: pass d1, d2 = getlincoef(dl[0], args), getlincoef(dl[1], args) if None not in [d1[0], d2[0]]: @@ -2579,7 +2578,7 @@ def analyzevars(block): l = vars[n]['charselector']['len'] try: l = str(eval(l, {}, params)) - except: + except Exception: pass vars[n]['charselector']['len'] = l @@ -2588,7 +2587,7 @@ def analyzevars(block): l = vars[n]['kindselector']['kind'] try: l = str(eval(l, {}, params)) - except: + except Exception: pass vars[n]['kindselector']['kind'] = l @@ -2819,7 +2818,7 @@ def analyzevars(block): try: kindselect['kind'] = eval( kindselect['kind'], {}, params) - except: + except Exception: pass vars[n]['kindselector'] = kindselect if charselect: @@ -3230,7 +3229,7 @@ def vars2fortran(block, vars, args, tab='', as_interface=False): try: v = eval(v) v = '(%s,%s)' % (v.real, v.imag) - except: + except Exception: pass vardef = '%s :: %s=%s' % (vardef, a, v) else: @@ -3335,8 +3334,7 @@ if __name__ == "__main__": if pyffilename: outmess('Writing fortran code to file %s\n' % repr(pyffilename), 0) pyf = crack2fortran(postlist) - f = open(pyffilename, 'w') - f.write(pyf) - f.close() + with open(pyffilename, 'w') as f: + f.write(pyf) if showblocklist: show(postlist) diff --git a/numpy/f2py/f2py_testing.py b/numpy/f2py/f2py_testing.py index c7041fe25..f5d5fa63d 100644 --- a/numpy/f2py/f2py_testing.py +++ b/numpy/f2py/f2py_testing.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function import sys import re -from numpy.testing.utils import jiffies, memusage +from numpy.testing import jiffies, memusage def cmdline(): diff --git a/numpy/f2py/src/fortranobject.c b/numpy/f2py/src/fortranobject.c index 8c8b4ae5d..96b08ea18 100644 --- a/numpy/f2py/src/fortranobject.c +++ b/numpy/f2py/src/fortranobject.c @@ -130,8 +130,7 @@ format_def(char *buf, Py_ssize_t size, FortranDataDef def) return -1; } - p[size] = ')'; - p++; + *p++ = ')'; size--; if (def.data == NULL) { @@ -591,21 +590,21 @@ static void f2py_report_on_array_copy_fromany(void) { * $Id: fortranobject.c,v 1.52 2005/07/11 07:44:20 pearu Exp $ */ +static int check_and_fix_dimensions(const PyArrayObject* arr, + const int rank, + npy_intp *dims); + static int -count_nonpos(const int rank, - const npy_intp *dims) { +count_negative_dimensions(const int rank, + const npy_intp *dims) { int i=0,r=0; while (i<rank) { - if (dims[i] <= 0) ++r; + if (dims[i] < 0) ++r; ++i; } return r; } -static int check_and_fix_dimensions(const PyArrayObject* arr, - const int rank, - npy_intp *dims); - #ifdef DEBUG_COPY_ND_ARRAY void dump_dims(int rank, npy_intp* dims) { int i; @@ -679,7 +678,7 @@ PyArrayObject* array_from_pyobj(const int type_num, || ((intent & F2PY_OPTIONAL) && (obj==Py_None)) ) { /* intent(cache), optional, intent(hide) */ - if (count_nonpos(rank,dims)) { + if (count_negative_dimensions(rank,dims) > 0) { int i; strcpy(mess, "failed to create intent(cache|hide)|optional array" "-- must have defined dimensions but got ("); @@ -720,8 +719,8 @@ PyArrayObject* array_from_pyobj(const int type_num, /* intent(cache) */ if (PyArray_ISONESEGMENT(arr) && PyArray_ITEMSIZE(arr)>=elsize) { - if (check_and_fix_dimensions(arr,rank,dims)) { - return NULL; /*XXX: set exception */ + if (check_and_fix_dimensions(arr, rank, dims)) { + return NULL; } if (intent & F2PY_INTENT_OUT) Py_INCREF(arr); @@ -742,8 +741,8 @@ PyArrayObject* array_from_pyobj(const int type_num, /* here we have always intent(in) or intent(inout) or intent(inplace) */ - if (check_and_fix_dimensions(arr,rank,dims)) { - return NULL; /*XXX: set exception */ + if (check_and_fix_dimensions(arr, rank, dims)) { + return NULL; } /* printf("intent alignement=%d\n", F2PY_GET_ALIGNMENT(intent)); @@ -843,8 +842,9 @@ PyArrayObject* array_from_pyobj(const int type_num, | NPY_ARRAY_FORCECAST, NULL); if (arr==NULL) return NULL; - if (check_and_fix_dimensions(arr,rank,dims)) - return NULL; /*XXX: set exception */ + if (check_and_fix_dimensions(arr, rank, dims)) { + return NULL; + } return arr; } @@ -855,11 +855,16 @@ PyArrayObject* array_from_pyobj(const int type_num, /*****************************************/ static -int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *dims) { +int check_and_fix_dimensions(const PyArrayObject* arr, const int rank, npy_intp *dims) +{ /* - This function fills in blanks (that are -1\'s) in dims list using + This function fills in blanks (that are -1's) in dims list using the dimensions from arr. It also checks that non-blank dims will match with the corresponding values in arr dimensions. + + Returns 0 if the function is successful. + + If an error condition is detected, an exception is set and 1 is returned. */ const npy_intp arr_size = (PyArray_NDIM(arr))?PyArray_Size((PyObject *)arr):1; #ifdef DEBUG_COPY_ND_ARRAY @@ -877,9 +882,10 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d d = PyArray_DIM(arr,i); if (dims[i] >= 0) { if (d>1 && dims[i]!=d) { - fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT - " but got %" NPY_INTP_FMT "\n", - i,dims[i], d); + PyErr_Format(PyExc_ValueError, + "%d-th dimension must be fixed to %" + NPY_INTP_FMT " but got %" NPY_INTP_FMT "\n", + i, dims[i], d); return 1; } if (!dims[i]) dims[i] = 1; @@ -890,9 +896,10 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d } for(i=PyArray_NDIM(arr);i<rank;++i) if (dims[i]>1) { - fprintf(stderr,"%d-th dimension must be %" NPY_INTP_FMT - " but got 0 (not defined).\n", - i,dims[i]); + PyErr_Format(PyExc_ValueError, + "%d-th dimension must be %" NPY_INTP_FMT + " but got 0 (not defined).\n", + i, dims[i]); return 1; } else if (free_axe<0) free_axe = i; @@ -903,9 +910,11 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d new_size *= dims[free_axe]; } if (new_size != arr_size) { - fprintf(stderr,"unexpected array size: new_size=%" NPY_INTP_FMT - ", got array with arr_size=%" NPY_INTP_FMT " (maybe too many free" - " indices)\n", new_size,arr_size); + PyErr_Format(PyExc_ValueError, + "unexpected array size: new_size=%" NPY_INTP_FMT + ", got array with arr_size=%" NPY_INTP_FMT + " (maybe too many free indices)\n", + new_size, arr_size); return 1; } } else if (rank==PyArray_NDIM(arr)) { @@ -916,9 +925,10 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d d = PyArray_DIM(arr,i); if (dims[i]>=0) { if (d > 1 && d!=dims[i]) { - fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT - " but got %" NPY_INTP_FMT "\n", - i,dims[i],d); + PyErr_Format(PyExc_ValueError, + "%d-th dimension must be fixed to %" + NPY_INTP_FMT " but got %" NPY_INTP_FMT "\n", + i, dims[i], d); return 1; } if (!dims[i]) dims[i] = 1; @@ -926,8 +936,10 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d new_size *= dims[i]; } if (new_size != arr_size) { - fprintf(stderr,"unexpected array size: new_size=%" NPY_INTP_FMT - ", got array with arr_size=%" NPY_INTP_FMT "\n", new_size,arr_size); + PyErr_Format(PyExc_ValueError, + "unexpected array size: new_size=%" NPY_INTP_FMT + ", got array with arr_size=%" NPY_INTP_FMT "\n", + new_size, arr_size); return 1; } } else { /* [[1,2]] -> [[1],[2]] */ @@ -939,8 +951,10 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d if (PyArray_DIM(arr,i)>1) ++effrank; if (dims[rank-1]>=0) if (effrank>rank) { - fprintf(stderr,"too many axes: %d (effrank=%d), expected rank=%d\n", - PyArray_NDIM(arr),effrank,rank); + PyErr_Format(PyExc_ValueError, + "too many axes: %d (effrank=%d), " + "expected rank=%d\n", + PyArray_NDIM(arr), effrank, rank); return 1; } @@ -950,9 +964,11 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d else d = PyArray_DIM(arr,j++); if (dims[i]>=0) { if (d>1 && d!=dims[i]) { - fprintf(stderr,"%d-th dimension must be fixed to %" NPY_INTP_FMT - " but got %" NPY_INTP_FMT " (real index=%d)\n", - i,dims[i],d,j-1); + PyErr_Format(PyExc_ValueError, + "%d-th dimension must be fixed to %" + NPY_INTP_FMT " but got %" NPY_INTP_FMT + " (real index=%d)\n", + i, dims[i], d, j-1); return 1; } if (!dims[i]) dims[i] = 1; @@ -968,13 +984,28 @@ int check_and_fix_dimensions(const PyArrayObject* arr,const int rank,npy_intp *d } for (i=0,size=1;i<rank;++i) size *= dims[i]; if (size != arr_size) { - fprintf(stderr,"unexpected array size: size=%" NPY_INTP_FMT ", arr_size=%" NPY_INTP_FMT - ", rank=%d, effrank=%d, arr.nd=%d, dims=[", - size,arr_size,rank,effrank,PyArray_NDIM(arr)); - for (i=0;i<rank;++i) fprintf(stderr," %" NPY_INTP_FMT,dims[i]); - fprintf(stderr," ], arr.dims=["); - for (i=0;i<PyArray_NDIM(arr);++i) fprintf(stderr," %" NPY_INTP_FMT,PyArray_DIM(arr,i)); - fprintf(stderr," ]\n"); + char msg[200]; + int len; + snprintf(msg, sizeof(msg), + "unexpected array size: size=%" NPY_INTP_FMT + ", arr_size=%" NPY_INTP_FMT + ", rank=%d, effrank=%d, arr.nd=%d, dims=[", + size, arr_size, rank, effrank, PyArray_NDIM(arr)); + for (i = 0; i < rank; ++i) { + len = strlen(msg); + snprintf(msg + len, sizeof(msg) - len, + " %" NPY_INTP_FMT, dims[i]); + } + len = strlen(msg); + snprintf(msg + len, sizeof(msg) - len, " ], arr.dims=["); + for (i = 0; i < PyArray_NDIM(arr); ++i) { + len = strlen(msg); + snprintf(msg + len, sizeof(msg) - len, + " %" NPY_INTP_FMT, PyArray_DIM(arr, i)); + } + len = strlen(msg); + snprintf(msg + len, sizeof(msg) - len, " ]\n"); + PyErr_SetString(PyExc_ValueError, msg); return 1; } } diff --git a/numpy/f2py/tests/__init__.py b/numpy/f2py/tests/__init__.py new file mode 100644 index 000000000..e69de29bb --- /dev/null +++ b/numpy/f2py/tests/__init__.py diff --git a/numpy/f2py/tests/src/common/block.f b/numpy/f2py/tests/src/common/block.f new file mode 100644 index 000000000..7ea7968fe --- /dev/null +++ b/numpy/f2py/tests/src/common/block.f @@ -0,0 +1,11 @@ + SUBROUTINE INITCB + DOUBLE PRECISION LONG + CHARACTER STRING + INTEGER OK + + COMMON /BLOCK/ LONG, STRING, OK + LONG = 1.0 + STRING = '2' + OK = 3 + RETURN + END diff --git a/numpy/f2py/tests/test_array_from_pyobj.py b/numpy/f2py/tests/test_array_from_pyobj.py index 48bb7c0f4..663fead6a 100644 --- a/numpy/f2py/tests/test_array_from_pyobj.py +++ b/numpy/f2py/tests/test_array_from_pyobj.py @@ -12,12 +12,12 @@ from numpy.testing import ( run_module_suite, assert_, assert_equal, SkipTest ) from numpy.core.multiarray import typeinfo -import util +from . import util wrap = None -def setup(): +def setup_module(): """ Build the required testing extension module @@ -294,7 +294,7 @@ class Array(object): return obj_attr[0] == self.arr_attr[0] -class test_intent(unittest.TestCase): +class TestIntent(object): def test_in_out(self): assert_equal(str(intent.in_.out), 'intent(in,out)') @@ -305,7 +305,7 @@ class test_intent(unittest.TestCase): assert_(not intent.in_.is_intent('c')) -class _test_shared_memory: +class _test_shared_memory(object): num2seq = [1, 2] num23seq = [[1, 2, 3], [4, 5, 6]] @@ -578,14 +578,12 @@ class _test_shared_memory: for t in _type_names: exec('''\ -class test_%s_gen(unittest.TestCase, - _test_shared_memory - ): - def setUp(self): +class TestGen_%s(_test_shared_memory): + def setup(self): self.type = Type(%r) array = lambda self,dims,intent,obj: Array(Type(%r),dims,intent,obj) ''' % (t, t, t)) if __name__ == "__main__": - setup() + setup_module() run_module_suite() diff --git a/numpy/f2py/tests/test_assumed_shape.py b/numpy/f2py/tests/test_assumed_shape.py index 725e7f0c1..371aab755 100644 --- a/numpy/f2py/tests/test_assumed_shape.py +++ b/numpy/f2py/tests/test_assumed_shape.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function import os from numpy.testing import run_module_suite, assert_, dec -import util +from . import util def _path(*a): diff --git a/numpy/f2py/tests/test_block_docstring.py b/numpy/f2py/tests/test_block_docstring.py new file mode 100644 index 000000000..c3f9dc856 --- /dev/null +++ b/numpy/f2py/tests/test_block_docstring.py @@ -0,0 +1,23 @@ +from __future__ import division, absolute_import, print_function + +import textwrap +from . import util + +from numpy.testing import run_module_suite, assert_equal + +class TestBlockDocString(util.F2PyTest): + code = """ + SUBROUTINE FOO() + INTEGER BAR(2, 3) + + COMMON /BLOCK/ BAR + RETURN + END + """ + + def test_block_docstring(self): + expected = "'i'-array(2,3)\n" + assert_equal(self.module.block.__doc__, expected) + +if __name__ == "__main__": + run_module_suite() diff --git a/numpy/f2py/tests/test_callback.py b/numpy/f2py/tests/test_callback.py index 6824a2042..ea29043ed 100644 --- a/numpy/f2py/tests/test_callback.py +++ b/numpy/f2py/tests/test_callback.py @@ -5,7 +5,7 @@ import textwrap from numpy import array from numpy.testing import run_module_suite, assert_, assert_equal, dec -import util +from . import util class TestF77Callback(util.F2PyTest): diff --git a/numpy/f2py/tests/test_common.py b/numpy/f2py/tests/test_common.py new file mode 100644 index 000000000..aaa35b678 --- /dev/null +++ b/numpy/f2py/tests/test_common.py @@ -0,0 +1,26 @@ +from __future__ import division, absolute_import, print_function + +import os + +from numpy.testing import run_module_suite, assert_array_equal, dec +import numpy as np +from . import util + + +def _path(*a): + return os.path.join(*((os.path.dirname(__file__),) + a)) + +class TestCommonBlock(util.F2PyTest): + sources = [_path('src', 'common', 'block.f')] + + def test_common_block(self): + self.module.initcb() + assert_array_equal(self.module.block.long_bn, + np.array(1.0, dtype=np.float64)) + assert_array_equal(self.module.block.string_bn, + np.array('2', dtype='|S1')) + assert_array_equal(self.module.block.ok, + np.array(3, dtype=np.int32)) + +if __name__ == "__main__": + run_module_suite() diff --git a/numpy/f2py/tests/test_kind.py b/numpy/f2py/tests/test_kind.py index 2552234a1..7cfe2e977 100644 --- a/numpy/f2py/tests/test_kind.py +++ b/numpy/f2py/tests/test_kind.py @@ -7,7 +7,7 @@ from numpy.f2py.crackfortran import ( _selected_int_kind_func as selected_int_kind, _selected_real_kind_func as selected_real_kind ) -import util +from . import util def _path(*a): diff --git a/numpy/f2py/tests/test_mixed.py b/numpy/f2py/tests/test_mixed.py index 9055083bf..c145a4b23 100644 --- a/numpy/f2py/tests/test_mixed.py +++ b/numpy/f2py/tests/test_mixed.py @@ -4,7 +4,7 @@ import os import textwrap from numpy.testing import run_module_suite, assert_, assert_equal, dec -import util +from . import util def _path(*a): diff --git a/numpy/f2py/tests/test_parameter.py b/numpy/f2py/tests/test_parameter.py index b6891756d..285b693a1 100644 --- a/numpy/f2py/tests/test_parameter.py +++ b/numpy/f2py/tests/test_parameter.py @@ -6,7 +6,7 @@ import math import numpy as np from numpy.testing import run_module_suite, dec, assert_raises, assert_equal -import util +from . import util def _path(*a): diff --git a/numpy/f2py/tests/test_regression.py b/numpy/f2py/tests/test_regression.py index 43a8de350..c34a5781c 100644 --- a/numpy/f2py/tests/test_regression.py +++ b/numpy/f2py/tests/test_regression.py @@ -6,7 +6,7 @@ import math import numpy as np from numpy.testing import run_module_suite, dec, assert_raises, assert_equal -import util +from . import util def _path(*a): diff --git a/numpy/f2py/tests/test_return_character.py b/numpy/f2py/tests/test_return_character.py index 7704e7d28..217b2c9dd 100644 --- a/numpy/f2py/tests/test_return_character.py +++ b/numpy/f2py/tests/test_return_character.py @@ -2,7 +2,7 @@ from __future__ import division, absolute_import, print_function from numpy import array from numpy.testing import run_module_suite, assert_, dec -import util +from . import util class TestReturnCharacter(util.F2PyTest): diff --git a/numpy/f2py/tests/test_return_complex.py b/numpy/f2py/tests/test_return_complex.py index 88ef83e94..73ced8ed8 100644 --- a/numpy/f2py/tests/test_return_complex.py +++ b/numpy/f2py/tests/test_return_complex.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function from numpy import array from numpy.compat import long from numpy.testing import run_module_suite, assert_, assert_raises, dec -import util +from . import util class TestReturnComplex(util.F2PyTest): diff --git a/numpy/f2py/tests/test_return_integer.py b/numpy/f2py/tests/test_return_integer.py index 00033d698..df8fc7c97 100644 --- a/numpy/f2py/tests/test_return_integer.py +++ b/numpy/f2py/tests/test_return_integer.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function from numpy import array from numpy.compat import long from numpy.testing import run_module_suite, assert_, assert_raises, dec -import util +from . import util class TestReturnInteger(util.F2PyTest): diff --git a/numpy/f2py/tests/test_return_logical.py b/numpy/f2py/tests/test_return_logical.py index f88a25d7a..221dc3cbd 100644 --- a/numpy/f2py/tests/test_return_logical.py +++ b/numpy/f2py/tests/test_return_logical.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function from numpy import array from numpy.compat import long from numpy.testing import run_module_suite, assert_, assert_raises, dec -import util +from . import util class TestReturnLogical(util.F2PyTest): diff --git a/numpy/f2py/tests/test_return_real.py b/numpy/f2py/tests/test_return_real.py index 57aa9badf..a81549083 100644 --- a/numpy/f2py/tests/test_return_real.py +++ b/numpy/f2py/tests/test_return_real.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function from numpy import array from numpy.compat import long from numpy.testing import run_module_suite, assert_, assert_raises, dec -import util +from . import util class TestReturnReal(util.F2PyTest): diff --git a/numpy/f2py/tests/test_size.py b/numpy/f2py/tests/test_size.py index aeb70486a..1fcad05a5 100644 --- a/numpy/f2py/tests/test_size.py +++ b/numpy/f2py/tests/test_size.py @@ -3,7 +3,7 @@ from __future__ import division, absolute_import, print_function import os from numpy.testing import run_module_suite, assert_equal, dec -import util +from . import util def _path(*a): @@ -15,6 +15,9 @@ class TestSizeSumExample(util.F2PyTest): @dec.slow def test_all(self): + r = self.module.foo([[]]) + assert_equal(r, [0], repr(r)) + r = self.module.foo([[1, 2]]) assert_equal(r, [3], repr(r)) @@ -26,6 +29,9 @@ class TestSizeSumExample(util.F2PyTest): @dec.slow def test_transpose(self): + r = self.module.trans([[]]) + assert_equal(r.T, [[]], repr(r)) + r = self.module.trans([[1, 2]]) assert_equal(r, [[1], [2]], repr(r)) @@ -34,6 +40,9 @@ class TestSizeSumExample(util.F2PyTest): @dec.slow def test_flatten(self): + r = self.module.flatten([[]]) + assert_equal(r, [], repr(r)) + r = self.module.flatten([[1, 2]]) assert_equal(r, [1, 2], repr(r)) diff --git a/numpy/f2py/tests/test_string.py b/numpy/f2py/tests/test_string.py index 10022ebb1..065861c0b 100644 --- a/numpy/f2py/tests/test_string.py +++ b/numpy/f2py/tests/test_string.py @@ -4,7 +4,7 @@ import os from numpy.testing import run_module_suite, assert_array_equal, dec import numpy as np -import util +from . import util def _path(*a): diff --git a/numpy/f2py/tests/util.py b/numpy/f2py/tests/util.py index fe608d898..55716a2eb 100644 --- a/numpy/f2py/tests/util.py +++ b/numpy/f2py/tests/util.py @@ -319,7 +319,7 @@ class F2PyTest(object): module = None module_name = None - def setUp(self): + def setup(self): if self.module is not None: return |