static PyObject* struct_items(PyObject *self, PyObject* args) { StructObject * const that = (StructObject*) self; if(!PyArg_ParseTuple(args, "")) return NULL; return PyDict_Items(that->dict); }
/*! Reloads Python interpreter and restarts loaded modules */ void reloadPython() { PyObject *sysModule = PyImport_ImportModule( "sys" ); PyObject *modules = PyObject_GetAttrString( sysModule, "modules" ); // This is a dictionary, so iterate trough it and reload all contained modules PyObject *mList = PyDict_Items( modules ); for( INT32 i = 0; i < PyList_Size( mList ); ++i ) PyImport_ReloadModule( PyList_GetItem( mList, i ) ); }
list dict_base::items() const { if (check_exact(this)) { return list(detail::new_reference( PyDict_Items(this->ptr()))); } else { return assume_list(this->attr("items")()); } }
static void SPOLStatement(char *func, PyObject *args, PyObject *kargs) { int i, n, nargs; PyObject *sargs; PyObject *klist; PyObject *kvar; PyObject *p, *q; char *s1, *s2; fprintf(spol_file, "%s", func); nargs = PyTuple_Size(args); sargs = PyObject_Str(args); s1 = PyString_AsString(sargs); n = strlen(s1); if (nargs == 1) { n = n-2; } else { n = n-1; } for (i = 0; i < n; i++) { fprintf(spol_file, "%c", s1[i]); } if (kargs) { klist = PyDict_Items(kargs); n = PyList_Size(klist); for (i = 0; i < n; i++) { if (nargs > 0 || i > 0) fprintf(spol_file, ", "); p = PyList_GetItem(klist, i); q = PyTuple_GetItem(p, 0); s2 = PyString_AsString(q); fprintf(spol_file, "%s=", s2); q = PyTuple_GetItem(p, 1); kvar = PyObject_Str(q); s2 = PyString_AsString(kvar); if (PyString_Check(q)) { fprintf(spol_file, "'%s'", s2); } else { fprintf(spol_file, "%s", s2); } Py_XDECREF(kvar); } Py_XDECREF(klist); } fprintf(spol_file, ")\n"); Py_XDECREF(sargs); return; }
static void _struct_build_repr(StructObject *that) { GString *str; PyObject *items; int i; g_assert(that->repr == NULL); str = g_string_new("Struct {"); /* safe, a Struct can't be empty */ items = PyDict_Items(that->dict); (void) PyList_Sort(items); for(i = 0; i < PyList_GET_SIZE(items); ++i) { PyObject *pair, *key, *value; pair = PyList_GET_ITEM(items, i); key = PyObject_Str(PyTuple_GET_ITEM(pair, 0)); value = PyObject_Str(PyTuple_GET_ITEM(pair, 1)); g_string_append_printf(str, " .%s = %s,", PyString_AS_STRING(key), PyString_AS_STRING(value)); Py_DECREF(key); Py_DECREF(value); } Py_DECREF(items); str->str[ str->len - 1 ] = ' '; /* replace the trailing ',' by a ' ' */ g_string_append_c(str, '}'); that->repr = PyString_FromStringAndSize(str->str, str->len); g_string_free(str, TRUE); }
static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return __Pyx_PyObject_CallMethod1((PyObject*)&PyDict_Type, PYIDENT("items"), d); else return PyDict_Items(d); }
static PyObject * lru_cache_make_key(PyObject *args, PyObject *kwds, int typed) { PyObject *key, *sorted_items; Py_ssize_t key_size, pos, key_pos; /* short path, key will match args anyway, which is a tuple */ if (!typed && !kwds) { Py_INCREF(args); return args; } if (kwds && PyDict_GET_SIZE(kwds) > 0) { sorted_items = PyDict_Items(kwds); if (!sorted_items) return NULL; if (PyList_Sort(sorted_items) < 0) { Py_DECREF(sorted_items); return NULL; } } else sorted_items = NULL; key_size = PyTuple_GET_SIZE(args); if (sorted_items) key_size += PyList_GET_SIZE(sorted_items); if (typed) key_size *= 2; if (sorted_items) key_size++; key = PyTuple_New(key_size); if (key == NULL) goto done; key_pos = 0; for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) { PyObject *item = PyTuple_GET_ITEM(args, pos); Py_INCREF(item); PyTuple_SET_ITEM(key, key_pos++, item); } if (sorted_items) { Py_INCREF(kwd_mark); PyTuple_SET_ITEM(key, key_pos++, kwd_mark); for (pos = 0; pos < PyList_GET_SIZE(sorted_items); ++pos) { PyObject *item = PyList_GET_ITEM(sorted_items, pos); Py_INCREF(item); PyTuple_SET_ITEM(key, key_pos++, item); } } if (typed) { for (pos = 0; pos < PyTuple_GET_SIZE(args); ++pos) { PyObject *item = (PyObject *)Py_TYPE(PyTuple_GET_ITEM(args, pos)); Py_INCREF(item); PyTuple_SET_ITEM(key, key_pos++, item); } if (sorted_items) { for (pos = 0; pos < PyList_GET_SIZE(sorted_items); ++pos) { PyObject *tp_items = PyList_GET_ITEM(sorted_items, pos); PyObject *item = (PyObject *)Py_TYPE(PyTuple_GET_ITEM(tp_items, 1)); Py_INCREF(item); PyTuple_SET_ITEM(key, key_pos++, item); } } } assert(key_pos == key_size); done: if (sorted_items) Py_DECREF(sorted_items); return key; }
static CYTHON_INLINE PyObject* __Pyx_PyDict_Items(PyObject* d) { if (PY_MAJOR_VERSION >= 3) return CALL_UNBOUND_METHOD(PyDict_Type, "items", d); else return PyDict_Items(d); }
//------------------------------------------------------------------------------------- PyObject* Map::__py_items(PyObject* self, PyObject* args) { return PyDict_Items(static_cast<Map*>(self)->pyDict_); }
static PyObject * Struct_repr(PyObject *self) { Py_ssize_t i; PyObject *inner_repr = NULL; PyObject *equals = NULL; PyObject *pieces = NULL, *result = NULL; PyObject *items = NULL, *s; PyTypeObject *type = Py_TYPE(self); i = Py_ReprEnter(self); if (i < 0) { return NULL; } if (i > 0) { inner_repr = str_from_string("..."); if (inner_repr == NULL) goto done; result = format_with_type(type, inner_repr); } else if (((PyDictObject *)self)->ma_used == 0) { result = format_with_type(type, NULL); } else { /* basically `dict_repr` but with keyword notation */ pieces = PyList_New(0); if (pieces == NULL) goto done; equals = str_from_string("="); if (equals == NULL) goto done; items = PyDict_Items(self); if (items == NULL) goto done; if (PyList_Sort(items) < 0) goto done; for (i = 0; i < PyList_GET_SIZE(items); i++) { PyObject *temp, *key, *value; int status; temp = PyList_GET_ITEM(items, i); key = PyTuple_GetItem(temp, 0); if (key == NULL) goto done; value = PyTuple_GetItem(temp, 1); if (value == NULL) goto done; /* Prevent repr from deleting value during key format. */ Py_INCREF(value); s = PyObject_Str(key); str_concat(&s, equals); str_concat_and_del(&s, PyObject_Repr(value)); Py_DECREF(value); if (s == NULL) goto done; status = PyList_Append(pieces, s); Py_DECREF(s); /* append created a new ref */ if (status < 0) goto done; } /* Paste them all together with ", " between. */ s = str_from_string(", "); if (s == NULL) goto done; inner_repr = str_join(s, pieces); Py_DECREF(s); if (inner_repr == NULL) goto done; result = format_with_type(type, inner_repr); } done: Py_XDECREF(inner_repr); Py_XDECREF(items); Py_XDECREF(pieces); Py_XDECREF(equals); Py_ReprLeave(self); return result; }
/** * Convert Python dict to 1x1 Matlab struct array. * * :param obj: Object to convert [Borrow reference] * * :note: If keys are not strings, their __repr__ is used instead! * Fields that fail to convert to strings are silently skipped. * Also, strings are chopped off at \x00 characters. */ mxArray *mx_from_py_dict(PyObject* obj) { mxArray *r; int dims[1] = { 1 }; PyObject *items; int nitems; int k; char *buf; int len; char **fieldnames; PyObject *repr = NULL; items = PyDict_Items(obj); if (!items) goto error; nitems = PyList_Size(items); fieldnames = mxCalloc(nitems, sizeof(char*)); for (k = 0; k < nitems; ++k) { PyObject *o; o = PyList_GetItem(items, k); if (o == NULL) goto error; o = PyTuple_GetItem(o, 0); if (o == NULL) goto error; if (PyString_Check(o)) { PyString_AsStringAndSize(o, &buf, &len); } else { repr = PyObject_Repr(o); if (repr == NULL) continue; /* ... FIXME */ buf = PyString_AsString(repr); len = strlen(buf); } fieldnames[k] = mxCalloc(len + 1, sizeof(char)); memcpy(fieldnames[k], buf, len); fieldnames[k][len] = '\0'; if (repr) { Py_DECREF(repr); repr = NULL; } } r = mxCreateStructArray(1, dims, nitems, (const char**)fieldnames); if (!r) goto error; for (k = 0; k < nitems; ++k) { PyObject *o; o = PyList_GetItem(items, k); if (o == NULL) goto error; o = PyTuple_GetItem(o, 1); if (o == NULL) goto error; mxSetFieldByNumber(r, 0, k, mx_from_py(o)); } Py_DECREF(items); return r; error: PyErr_Clear(); if (items) { Py_DECREF(items); } return mx_from_py_unknown(obj); }
PyObject *py_gen_do_trigs(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] ={ "type","ch","obj","room","exit","cmd","arg","opts",NULL }; char *type = NULL; char *cmd = NULL; char *arg = NULL; PyObject *pych = NULL; PyObject *pyobj = NULL; PyObject *pyroom = NULL; PyObject *pyexit = NULL; PyObject *pyopts = NULL; LIST *opts = NULL; CHAR_DATA *ch = NULL; OBJ_DATA *obj = NULL; ROOM_DATA *room = NULL; EXIT_DATA *exit = NULL; void *me = NULL; int me_type = -1; bool fail = FALSE; // first, parse all of our arguments if(!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOOssO", kwlist, &type, &pych, &pyobj, &pyroom, &pyexit, &cmd, &arg, &pyopts)) { PyErr_Format(PyExc_TypeError, "do_trigs supplied invalid arguments."); return NULL; } // make sure we exist, and are of a valid type if(PyChar_Check(self)) { me = PyChar_AsChar(self); me_type = TRIGVAR_CHAR; } else if(PyObj_Check(self)) { me = PyObj_AsObj(self); me_type = TRIGVAR_OBJ; } else if(PyRoom_Check(self)) { me = PyRoom_AsRoom(self); me_type = TRIGVAR_ROOM; } // did we find a character? if(me == NULL) { PyErr_Format(PyExc_TypeError,"do_trigs owner does not exist."); return NULL; } // make sure ch is of the specified type if(pych!=NULL && (!PyChar_Check(pych) || (ch=PyChar_AsChar(pych)) == NULL)){ PyErr_Format(PyExc_TypeError,"do_trigs expects ch to be character."); return NULL; } // make sure obj is of the specified type if(pyobj!=NULL && (!PyObj_Check(pyobj) || (obj=PyObj_AsObj(pyobj)) == NULL)){ PyErr_Format(PyExc_TypeError,"do_trigs expects obj to be object."); return NULL; } // make sure room is of the specified type if(pyroom!=NULL&&(!PyRoom_Check(pyroom)||(room=PyRoom_AsRoom(pyroom))==NULL)){ PyErr_Format(PyExc_TypeError,"do_trigs expects room to be room."); return NULL; } // make sure exit is of the specified type if(pyexit!=NULL&&(!PyExit_Check(pyexit)||(exit=PyExit_AsExit(pyexit))==NULL)){ PyErr_Format(PyExc_TypeError,"do_trigs expects exit to be an exit."); return NULL; } // parse opts if(pyopts != NULL && !PyDict_Check(pyopts)) { PyErr_Format(PyExc_TypeError,"do_trigs expects opts to be a dict."); return NULL; } else if(pyopts != NULL) { PyObject *pairs = PyDict_Items(pyopts); int i = 0; opts = newList(); // go through each pair and add it to the pyopts list for(; i < PyList_Size(pairs); i++) { PyObject *pair = PyList_GetItem(pairs, i); PyObject *pykey = PyTuple_GetItem(pair, 0); PyObject *pyval = PyTuple_GetItem(pair, 1); OPT_VAR *opt = NULL; char *key = NULL; // make sure the key is a string if(PyString_Check(pykey)) key = PyString_AsString(pykey); else { PyErr_Format(PyExc_TypeError, "do_trigs opt keys must be strings."); fail = TRUE; break; } // check to make sure the val is a valid type if(PyChar_Check(pyval)) { CHAR_DATA *val = PyChar_AsChar(pyval); if(val != NULL) opt = newOptVar(key, val, TRIGVAR_CHAR); else { PyErr_Format(PyExc_TypeError,"%s opt provided nonexistent char.",key); fail = TRUE; break; } } else if(PyObj_Check(pyval)) { OBJ_DATA *val = PyObj_AsObj(pyval); if(val != NULL) opt = newOptVar(key, val, TRIGVAR_OBJ); else { PyErr_Format(PyExc_TypeError,"%s opt provided nonexistent obj.", key); fail = TRUE; break; } } else if(PyRoom_Check(pyval)) { ROOM_DATA *val = PyRoom_AsRoom(pyval); if(val != NULL) opt = newOptVar(key, val, TRIGVAR_ROOM); else { PyErr_Format(PyExc_TypeError,"%s opt provided nonexistent room.",key); fail = TRUE; break; } } else { PyErr_Format(PyExc_TypeError,"%s opt provided invalid value.",key); fail = TRUE; break; } // append the opt to the opt list listPut(opts, opt); } Py_DECREF(pairs); } // did everything succeed? if(fail == FALSE) gen_do_trigs(me,me_type,type,ch,obj,room,exit,cmd,arg,opts); // garbage collection if(opts != NULL) deleteListWith(opts, deleteOptVar); if(fail == TRUE) return NULL; return Py_BuildValue(""); }
//------------------------------------------------------------------------- // Converts a Python variable into an IDC variable // This function returns on one CIP_XXXX int pyvar_to_idcvar( const ref_t &py_var, idc_value_t *idc_var, int *gvar_sn) { PYW_GIL_CHECK_LOCKED_SCOPE(); // None / NULL if ( py_var == NULL || py_var.o == Py_None ) { idc_var->set_long(0); } // Numbers? else if ( PyW_GetNumberAsIDC(py_var.o, idc_var) ) { return CIP_OK; } // String else if ( PyString_Check(py_var.o) ) { idc_var->_set_string(PyString_AsString(py_var.o), PyString_Size(py_var.o)); } // Boolean else if ( PyBool_Check(py_var.o) ) { idc_var->set_long(py_var.o == Py_True ? 1 : 0); } // Float else if ( PyFloat_Check(py_var.o) ) { double dresult = PyFloat_AsDouble(py_var.o); ieee_realcvt((void *)&dresult, idc_var->e, 3); idc_var->vtype = VT_FLOAT; } // void* else if ( PyCObject_Check(py_var.o) ) { idc_var->set_pvoid(PyCObject_AsVoidPtr(py_var.o)); } // Python list? else if ( PyList_CheckExact(py_var.o) || PyW_IsSequenceType(py_var.o) ) { // Create the object VarObject(idc_var); // Determine list size and type bool is_seq = !PyList_CheckExact(py_var.o); Py_ssize_t size = is_seq ? PySequence_Size(py_var.o) : PyList_Size(py_var.o); bool ok = true; qstring attr_name; // Convert each item for ( Py_ssize_t i=0; i<size; i++ ) { // Get the item ref_t py_item; if ( is_seq ) py_item = newref_t(PySequence_GetItem(py_var.o, i)); else py_item = borref_t(PyList_GetItem(py_var.o, i)); // Convert the item into an IDC variable idc_value_t v; ok = pyvar_to_idcvar(py_item, &v, gvar_sn) >= CIP_OK; if ( ok ) { // Form the attribute name newref_t py_int(PyInt_FromSsize_t(i)); ok = PyW_ObjectToString(py_int.o, &attr_name); if ( !ok ) break; // Store the attribute VarSetAttr(idc_var, attr_name.c_str(), &v); } if ( !ok ) break; } return ok ? CIP_OK : CIP_FAILED; } // Dictionary: we convert to an IDC object else if ( PyDict_Check(py_var.o) ) { // Create an empty IDC object VarObject(idc_var); // Get the dict.items() list newref_t py_items(PyDict_Items(py_var.o)); // Get the size of the list qstring key_name; bool ok = true; Py_ssize_t size = PySequence_Size(py_items.o); for ( Py_ssize_t i=0; i<size; i++ ) { // Get item[i] -> (key, value) PyObject *py_item = PyList_GetItem(py_items.o, i); // Extract key/value newref_t key(PySequence_GetItem(py_item, 0)); newref_t val(PySequence_GetItem(py_item, 1)); // Get key's string representation PyW_ObjectToString(key.o, &key_name); // Convert the attribute into an IDC value idc_value_t v; ok = pyvar_to_idcvar(val, &v, gvar_sn) >= CIP_OK; if ( ok ) { // Store the attribute VarSetAttr(idc_var, key_name.c_str(), &v); } if ( !ok ) break; } return ok ? CIP_OK : CIP_FAILED; } // Possible function? else if ( PyCallable_Check(py_var.o) ) { idc_var->clear(); idc_var->vtype = VT_FUNC; idc_var->funcidx = -1; // Does not apply return CIP_OK; } // Objects: // - pyidc_cvt objects: int64, byref, opaque // - other python objects else { // Get the type int cvt_id = get_pyidc_cvt_type(py_var.o); switch ( cvt_id ) { // // INT64 // case PY_ICID_INT64: { // Get the value attribute ref_t attr(PyW_TryGetAttrString(py_var.o, S_PY_IDCCVT_VALUE_ATTR)); if ( attr == NULL ) return false; idc_var->set_int64(PyLong_AsLongLong(attr.o)); return CIP_OK; } // // BYREF // case PY_ICID_BYREF: { // BYREF always require this parameter if ( gvar_sn == NULL ) return CIP_FAILED; // Get the value attribute ref_t attr(PyW_TryGetAttrString(py_var.o, S_PY_IDCCVT_VALUE_ATTR)); if ( attr == NULL ) return CIP_FAILED; // Create a global variable char buf[MAXSTR]; qsnprintf(buf, sizeof(buf), S_PY_IDC_GLOBAL_VAR_FMT, *gvar_sn); idc_value_t *gvar = add_idc_gvar(buf); // Convert the python value into the IDC global variable bool ok = pyvar_to_idcvar(attr, gvar, gvar_sn) >= CIP_OK; if ( ok ) { (*gvar_sn)++; // Create a reference to this global variable VarRef(idc_var, gvar); } return ok ? CIP_OK : CIP_FAILED; } // // OPAQUE // case PY_ICID_OPAQUE: { if ( !wrap_PyObject_ptr(py_var, idc_var) ) return CIP_FAILED; return CIP_OK_OPAQUE; } // // Other objects // default: // A normal object? newref_t py_dir(PyObject_Dir(py_var.o)); Py_ssize_t size = PyList_Size(py_dir.o); if ( py_dir == NULL || !PyList_Check(py_dir.o) || size == 0 ) return CIP_FAILED; // Create the IDC object VarObject(idc_var); for ( Py_ssize_t i=0; i<size; i++ ) { borref_t item(PyList_GetItem(py_dir.o, i)); const char *field_name = PyString_AsString(item.o); if ( field_name == NULL ) continue; size_t len = strlen(field_name); // Skip private attributes if ( (len > 2 ) && (strncmp(field_name, "__", 2) == 0 ) && (strncmp(field_name+len-2, "__", 2) == 0) ) { continue; } idc_value_t v; // Get the non-private attribute from the object newref_t attr(PyObject_GetAttrString(py_var.o, field_name)); if (attr == NULL // Convert the attribute into an IDC value || pyvar_to_idcvar(attr, &v, gvar_sn) < CIP_OK) { return CIP_FAILED; } // Store the attribute VarSetAttr(idc_var, field_name, &v); } } } return CIP_OK; }
void python_to_mathematica_object(PyObject *obj) { if(PyBool_Check(obj)) { if(obj==Py_True) MLPutSymbol(stdlink, "True"); else MLPutSymbol(stdlink, "False"); return; } if(PyInt_Check(obj)) { MLPutLongInteger(stdlink, PyInt_AsLong(obj)); return; } if(PyLong_Check(obj)) { #ifdef PYTHON25 Py_ssize_t length; #else int length; #endif char *str, *mat_expr; PyObject *long_as_str; long_as_str = PyObject_CallMethod(obj, "__str__", NULL); PyString_AsStringAndSize(long_as_str, &str, &length); MLPutFunction(stdlink, "ToExpression", 1); MLPutString(stdlink, str); Py_DECREF(long_as_str); return; } if(obj==Py_None) { MLPutSymbol(stdlink, "Null"); return; } if(PyFloat_Check(obj)) { MLPutDouble(stdlink, (double)PyFloat_AsDouble(obj)); return; } if(PyComplex_Check(obj)) { MLPutFunction(stdlink, "Complex", 2); MLPutDouble(stdlink, (double)PyComplex_RealAsDouble(obj)); MLPutDouble(stdlink, (double)PyComplex_ImagAsDouble(obj)); return; } if(PyString_Check(obj)) { char *str; #ifdef PYTHON25 Py_ssize_t length; #else int length; #endif PyString_AsStringAndSize(obj, &str, &length); MLPutByteString(stdlink, (unsigned char *)str, length); return; } if(PyUnicode_Check(obj)) { MLPutUnicodeString(stdlink, PyUnicode_AsUnicode(obj), PyUnicode_GetSize(obj) ); return; } if(PyTuple_Check(obj)) { mat_process_iterable_object(obj, "Can't get iterator for 'tuple'"); return; } if(PyList_Check(obj)) { mat_process_iterable_object(obj, "Can't get iterator for 'list'"); return; } #ifndef PYTHON23 if(PyObject_TypeCheck(obj, &PySet_Type)) { mat_process_iterable_object(obj, "Can't get iterator for 'set'"); return; } #endif if(PyDict_Check(obj)) { PyObject *items; items = PyDict_Items(obj); python_to_mathematica_object(items); Py_DECREF(items); return; } // This should ideally print info, like type of the object, that // can't be converted. MLPutString(stdlink, "Object type can't be converted!"); }