static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kw)
{
    PyObject *ret;
    PyObject *argappl = NULL, *kwappl = NULL;

    assert (PyCallable_Check(pto->fn));
    assert (PyTuple_Check(pto->args));
    assert (pto->kw == Py_None  ||  PyDict_Check(pto->kw));

    if (PyTuple_GET_SIZE(pto->args) == 0) {
        argappl = args;
        Py_INCREF(args);
    } else if (PyTuple_GET_SIZE(args) == 0) {
        argappl = pto->args;
        Py_INCREF(pto->args);
    } else {
        argappl = PySequence_Concat(pto->args, args);
        if (argappl == NULL)
            return NULL;
    }

    if (pto->kw == Py_None) {
        kwappl = kw;
        Py_XINCREF(kw);
    } else {
        kwappl = PyDict_Copy(pto->kw);
        if (kwappl == NULL) {
            Py_DECREF(argappl);
            return NULL;
        }
        if (kw != NULL) {
            if (PyDict_Merge(kwappl, kw, 1) != 0) {
                Py_DECREF(argappl);
                Py_DECREF(kwappl);
                return NULL;
            }
        }
    }

    ret = PyObject_Call(pto->fn, argappl, kwappl);
    Py_DECREF(argappl);
    Py_XDECREF(kwappl);
    return ret;
}
Example #2
0
static int green_setdict(PyGreenlet* self, PyObject* val, void* c)
{
	PyObject* tmp;

	if (val == NULL) {
		PyErr_SetString(PyExc_TypeError, "__dict__ may not be deleted");
		return -1;
	}
	if (!PyDict_Check(val)) {
		PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary");
		return -1;
	}
	tmp = self->dict;
	Py_INCREF(val);
	self->dict = val;
	Py_XDECREF(tmp);
	return 0;
}
Example #3
0
/* Error.__reduce_ex__
 *
 * The method is required to make exceptions picklable: set the cursor
 * attribute to None. Only working from Py 2.5: previous versions
 * would require implementing __getstate__, and as of 2012 it's a little
 * bit too late to care. */
static PyObject *
psyco_error_reduce_ex(PyObject *self, PyObject *args)
{
    PyObject *proto = NULL;
    PyObject *super = NULL;
    PyObject *tuple = NULL;
    PyObject *dict = NULL;
    PyObject *rv = NULL;

    /* tuple = Exception.__reduce_ex__(self, proto) */
    if (!PyArg_ParseTuple(args, "O", &proto)) {
        goto error;
    }
    if (!(super = PyObject_GetAttrString(PyExc_Exception, "__reduce_ex__"))) {
        goto error;
    }
    if (!(tuple = PyObject_CallFunctionObjArgs(super, self, proto, NULL))) {
        goto error;
    }

    /* tuple[2]['cursor'] = None
     *
     * If these checks fail, we can still return a valid object. Pickle
     * will likely fail downstream, but there's nothing else we can do here */
    if (!PyTuple_Check(tuple)) { goto exit; }
    if (3 > PyTuple_GET_SIZE(tuple)) { goto exit; }
    dict = PyTuple_GET_ITEM(tuple, 2);      /* borrowed */
    if (!PyDict_Check(dict)) { goto exit; }

    /* Modify the tuple inplace and return it */
    if (0 != PyDict_SetItemString(dict, "cursor", Py_None)) {
        goto error;
    }

exit:
    rv = tuple;
    tuple = NULL;

error:
    Py_XDECREF(tuple);
    Py_XDECREF(super);

    return rv;
}
Example #4
0
static PyObject* set_rtoinfo(PyObject* dummy, PyObject* args)
{
	PyObject* ret = 0;
	PyObject* dict;
	PyObject* oassoc_id;
	PyObject* oinitial;
	PyObject* omin;
	PyObject* omax;

	int fd;
	struct sctp_rtoinfo v;
	int ok;
	
	ok = PyArg_ParseTuple(args, "iO", &fd, &dict) && PyDict_Check(dict);
	ok = ok && (oassoc_id = PyDict_GetItemString(dict, "assoc_id"));
	ok = ok && (oinitial = PyDict_GetItemString(dict, "initial"));
	ok = ok && (omin = PyDict_GetItemString(dict, "min"));
	ok = ok && (omax = PyDict_GetItemString(dict, "max"));
	ok = ok && PyInt_Check(oassoc_id);
	ok = ok && PyInt_Check(oinitial);
	ok = ok && PyInt_Check(omin);
	ok = ok && PyInt_Check(omax);

	if (! ok) {
		return ret;
	}

	bzero(&v, sizeof(v));
	v.srto_assoc_id = PyInt_AsLong(oassoc_id);
	v.srto_initial = PyInt_AsLong(oinitial);
	v.srto_min = PyInt_AsLong(omin);
	v.srto_max = PyInt_AsLong(omax);

	if (setsockopt(fd, SOL_SCTP, SCTP_RTOINFO, &v, sizeof(v))) {
		PyErr_SetFromErrno(PyExc_IOError);
	} else {
		PyDict_SetItemString(dict, "initial", PyInt_FromLong(v.srto_initial));
		PyDict_SetItemString(dict, "max", PyInt_FromLong(v.srto_max));
		PyDict_SetItemString(dict, "min", PyInt_FromLong(v.srto_min));
		ret = Py_None; Py_INCREF(ret);
	}

	return ret;
}
Example #5
0
static PyObject *
partial_call(partialobject *pto, PyObject *args, PyObject *kwargs)
{
    PyObject *kwargs2, *res;

    assert (PyCallable_Check(pto->fn));
    assert (PyTuple_Check(pto->args));
    assert (PyDict_Check(pto->kw));

    if (PyDict_GET_SIZE(pto->kw) == 0) {
        /* kwargs can be NULL */
        kwargs2 = kwargs;
        Py_XINCREF(kwargs2);
    }
    else {
        /* bpo-27840, bpo-29318: dictionary of keyword parameters must be
           copied, because a function using "**kwargs" can modify the
           dictionary. */
        kwargs2 = PyDict_Copy(pto->kw);
        if (kwargs2 == NULL) {
            return NULL;
        }

        if (kwargs != NULL) {
            if (PyDict_Merge(kwargs2, kwargs, 1) != 0) {
                Py_DECREF(kwargs2);
                return NULL;
            }
        }
    }


    if (pto->use_fastcall) {
        res = partial_fastcall(pto,
                               &PyTuple_GET_ITEM(args, 0),
                               PyTuple_GET_SIZE(args),
                               kwargs2);
    }
    else {
        res = partial_call_impl(pto, args, kwargs2);
    }
    Py_XDECREF(kwargs2);
    return res;
}
Example #6
0
PyObject* cpu_set_gpreg(JitCpu* self, PyObject *args)
{
    PyObject* dict;
    PyObject *d_key, *d_value = NULL;
    Py_ssize_t pos = 0;
    const char *d_key_name;
    uint32_t val32;
    uint64_t val64;
    unsigned int i, found;

    if (!PyArg_ParseTuple(args, "O", &dict))
	    RAISE(PyExc_TypeError,"Cannot parse arguments");
    if(!PyDict_Check(dict))
	    RAISE(PyExc_TypeError, "arg must be dict");
    while(PyDict_Next(dict, &pos, &d_key, &d_value)){
	    PyGetStr(d_key_name, d_key);
	    found = 0;
	    for (i=0; i < sizeof(gpreg_dict)/sizeof(reg_dict); i++){
		    if (strcmp(d_key_name, gpreg_dict[i].name))
			    continue;
		    found = 1;
		    switch (gpreg_dict[i].size) {
			    default:
				    RAISE(PyExc_TypeError, "Unsupported size");
				    break;
			    case 32:
				    PyGetInt_uint32_t(d_value, val32);
				    *((uint32_t*)(((char*)(self->cpu)) + gpreg_dict[i].offset)) = val32;
				    break;
			    case 64:
				    PyGetInt_uint64_t(d_value, val64);
				    *((uint64_t*)(((char*)(self->cpu)) + gpreg_dict[i].offset)) = val64;
				    break;
		    }
	    }

	    if (found)
		    continue;
	    fprintf(stderr, "unknown key: %s\n", d_key_name);
	    RAISE(PyExc_ValueError, "unknown reg");
    }
    Py_INCREF(Py_None);
    return Py_None;
}
Example #7
0
static PyObject *
partial_repr(partialobject *pto)
{
    PyObject *result = NULL;
    PyObject *arglist;
    Py_ssize_t i, n;
    PyObject *key, *value;
    int status;

    status = Py_ReprEnter((PyObject *)pto);
    if (status != 0) {
        if (status < 0)
            return NULL;
        return PyUnicode_FromString("...");
    }

    arglist = PyUnicode_FromString("");
    if (arglist == NULL)
        goto done;
    /* Pack positional arguments */
    assert (PyTuple_Check(pto->args));
    n = PyTuple_GET_SIZE(pto->args);
    for (i = 0; i < n; i++) {
        Py_SETREF(arglist, PyUnicode_FromFormat("%U, %R", arglist,
                                        PyTuple_GET_ITEM(pto->args, i)));
        if (arglist == NULL)
            goto done;
    }
    /* Pack keyword arguments */
    assert (PyDict_Check(pto->kw));
    for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
        Py_SETREF(arglist, PyUnicode_FromFormat("%U, %U=%R", arglist,
                                                key, value));
        if (arglist == NULL)
            goto done;
    }
    result = PyUnicode_FromFormat("%s(%R%U)", Py_TYPE(pto)->tp_name,
                                  pto->fn, arglist);
    Py_DECREF(arglist);

 done:
    Py_ReprLeave((PyObject *)pto);
    return result;
}
Example #8
0
int py_convert(lua_State *L, PyObject *o, int withnone)
{
	int ret = 0;
	if (o == Py_None) {	
		if (withnone) {
			lua_pushliteral(L, "Py_None");
			lua_rawget(L, LUA_REGISTRYINDEX);
			if (lua_isnil(L, -1)) {
				lua_pop(L, 1);
				luaL_error(L, "lost none from registry");
			}
		} else {
			/* Not really needed, but this way we may check
			 * for errors with ret == 0. */
			lua_pushnil(L);
			ret = 1;
		}
	} else if (o == Py_True) {
		lua_pushboolean(L, 1);
	} else if (o == Py_False) {
		lua_pushboolean(L, 0);
	} else if (PyString_Check(o)) {
		char *s;
		int len;
		PyString_AsStringAndSize(o, &s, &len);
		lua_pushlstring(L, s, len);
		ret = 1;
	} else if (PyInt_Check(o) || PyFloat_Check(o)) {
		lua_pushnumber(L, (lua_Number)PyInt_AsLong(o));
		ret = 1;
	} else if (LuaObject_Check(o)) {
		lua_rawgeti(L, LUA_REGISTRYINDEX, ((LuaObject*)o)->ref);
		ret = 1;
	} else {
		int asindx = 0;
		if (PyDict_Check(o) || PyList_Check(o) || PyTuple_Check(o))
			asindx = 1;
		ret = py_convert_custom(L, o, asindx);
		if (ret && !asindx &&
		    (PyFunction_Check(o) || PyCFunction_Check(o)))
			lua_pushcclosure(L, py_asfunc_call, 1);
	}
	return ret;
}
Example #9
0
static PyObject* get_paddrinfo(PyObject* dummy, PyObject* args)
{
	PyObject* ret = 0;
	PyObject* dict;
	PyObject* oassoc_id;
	PyObject* oaddresstuple;
	const char* address;
	int port;
	int fd;
	int slen_dummy;
	struct sctp_paddrinfo v;
	socklen_t lv = sizeof(v);
	int ok;
	
	ok = PyArg_ParseTuple(args, "iO", &fd, &dict) && PyDict_Check(dict);
	ok = ok && (oassoc_id = PyDict_GetItemString(dict, "assoc_id"));
	ok = ok && (oaddresstuple = PyDict_GetItemString(dict, "sockaddr"));
	ok = ok && PyInt_Check(oassoc_id);
	ok = ok && PyArg_ParseTuple(oaddresstuple, "si", &address, &port);

	if (! ok) {
		return ret;
	}

	bzero(&v, sizeof(v));
	v.spinfo_assoc_id = PyInt_AsLong(oassoc_id);
	if (! to_sockaddr(address, port, (struct sockaddr*) &(v.spinfo_address), &slen_dummy)) {
		PyErr_SetString(PyExc_ValueError, "address could not be translated");
		return ret;
	}

	if (getsockopt(fd, SOL_SCTP, SCTP_GET_PEER_ADDR_INFO, &v, &lv)) {
		PyErr_SetFromErrno(PyExc_IOError);
	} else {
		PyDict_SetItemString(dict, "state", PyInt_FromLong(v.spinfo_state));
		PyDict_SetItemString(dict, "cwnd", PyInt_FromLong(v.spinfo_cwnd));
		PyDict_SetItemString(dict, "srtt", PyInt_FromLong(v.spinfo_srtt));
		PyDict_SetItemString(dict, "rto", PyInt_FromLong(v.spinfo_rto));
		PyDict_SetItemString(dict, "mtu", PyInt_FromLong(v.spinfo_mtu));
		ret = Py_None; Py_INCREF(ret);
	}

	return ret;
}
/**
 *******************************************************************************************************
 * This function checks for metadata and if present set it into the
 * as_operations.
 *
 * @param py_meta               The dictionary of metadata.
 * @param ops                   The as_operations object.
 * @param err                   The as_error to be populated by the function
 *                              with the encountered error if any.
 *
 * Returns nothing.
 *******************************************************************************************************
 */
static
void AerospikeClient_CheckForMeta(PyObject * py_meta, as_operations * ops, as_error *err)
{
	if ( py_meta && PyDict_Check(py_meta) ) {
		PyObject * py_gen = PyDict_GetItemString(py_meta, "gen");
		PyObject * py_ttl = PyDict_GetItemString(py_meta, "ttl");
        uint32_t ttl = 0;
        uint16_t gen = 0; 
		if ( py_ttl != NULL ){
			if ( PyInt_Check(py_ttl) ) {
				ttl = (uint32_t) PyInt_AsLong(py_ttl);
			} else if ( PyLong_Check(py_ttl) ) {
				ttl = (uint32_t) PyLong_AsLongLong(py_ttl);
			} else {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Ttl should be an int or long");
			}

            if((uint32_t)-1 == ttl) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for ttl exceeds sys.maxsize");
                return;
            }
            ops->ttl = ttl;
		}

		if( py_gen != NULL ){
			if ( PyInt_Check(py_gen) ) {
				gen = (uint16_t) PyInt_AsLong(py_gen);
			} else if ( PyLong_Check(py_gen) ) {
				gen = (uint16_t) PyLong_AsLongLong(py_gen);
			} else {
				as_error_update(err, AEROSPIKE_ERR_PARAM, "Generation should be an int or long");
			}

            if((uint16_t)-1 == gen) {
                as_error_update(err, AEROSPIKE_ERR_PARAM, "integer value for gen exceeds sys.maxsize");
                return;
            }
            ops->gen = gen;
		}
	} else {
		as_error_update(err, AEROSPIKE_ERR_PARAM, "Metadata should be of type dictionary");
	}
}
static int Nuitka_Function_set_kwdefaults( Nuitka_FunctionObject *object, PyObject *value )
{
    if ( value == NULL )
    {
        value = Py_None;
    }

    if (unlikely( value != Py_None && PyDict_Check( value ) == false ))
    {
        PyErr_Format( PyExc_TypeError, "__kwdefaults__ must be set to a dict object" );
        return -1;
    }

    PyObject *old = object->m_kwdefaults;
    object->m_kwdefaults = INCREASE_REFCOUNT( value );
    Py_DECREF( old );

    return 0;
}
Example #12
0
void
PyFrame_FastToLocals(PyFrameObject *f)
{
	/* Merge fast locals into f->f_locals */
	PyObject *locals, *map;
	PyObject **fast;
	PyObject *error_type, *error_value, *error_traceback;
	int j;
	if (f == NULL)
		return;
	locals = f->f_locals;
	if (locals == NULL) {
		locals = f->f_locals = PyDict_New();
		if (locals == NULL) {
			PyErr_Clear(); /* Can't report it :-( */
			return;
		}
	}
	if (f->f_nlocals == 0)
		return;
	map = f->f_code->co_varnames;
	if (!PyDict_Check(locals) || !PyTuple_Check(map))
		return;
	PyErr_Fetch(&error_type, &error_value, &error_traceback);
	fast = f->f_localsplus;
	j = PyTuple_Size(map);
	if (j > f->f_nlocals)
		j = f->f_nlocals;
	for (; --j >= 0; ) {
		PyObject *key = PyTuple_GetItem(map, j);
		PyObject *value = fast[j];
		if (value == NULL) {
			PyErr_Clear();
			if (PyDict_DelItem(locals, key) != 0)
				PyErr_Clear();
		}
		else {
			if (PyDict_SetItem(locals, key, value) != 0)
				PyErr_Clear();
		}
	}
	PyErr_Restore(error_type, error_value, error_traceback);
}
Example #13
0
GeoPoint Python::ReadLonLat(PyObject *py_location) {
  if (!PyDict_Check(py_location)) {
    PyErr_SetString(PyExc_TypeError, "Location is not a dictionary.");
    return GeoPoint::Invalid();
  }

  PyObject *py_latitude = PyDict_GetItemString(py_location, "latitude"),
           *py_longitude = PyDict_GetItemString(py_location, "longitude");

  if (!PyNumber_Check(py_latitude) || !PyNumber_Check(py_longitude)) {
    PyErr_SetString(PyExc_TypeError, "Failed to parse location.");
    return GeoPoint::Invalid();
  }

  GeoPoint location(Angle::Degrees(PyFloat_AsDouble(py_longitude)),
                    Angle::Degrees(PyFloat_AsDouble(py_latitude)));

  return location;
}
Example #14
0
/*static*/
QVariant PythonScript::PythonToVariant(PyObject * o)
{
    QVariantList list;
    QVariantMap map;
    PyObject * key, * value;
    Py_ssize_t i = 0;
    QString str;

    if (o == Py_None)
        return QVariant();
    // in Python 3.x, the PyInt_* were removed in favor of PyLong_*
#if PY_MAJOR_VERSION < 3
    if (PyInt_Check(o)) return QVariant((int)PyInt_AsLong(o));
#endif
    if (PyBool_Check(o)) return QVariant((o == Py_True));
    if (PyLong_Check(o)) return QVariant((qlonglong)PyLong_AsLong(o));
    if (PyFloat_Check(o)) return QVariant(PyFloat_AsDouble(o));
    if (asQString(o, str)) return str;
    if (PyTuple_Check(o)) {
        for (i = 0; i < PyTuple_Size(o); ++i) {
            list.append(PythonToVariant(PyTuple_GetItem(o, i)));
        }
        return list;
    }
    if (PyList_Check(o)) {
        for (i = 0; i < PyList_Size(o); ++i) {
            list.append(PythonToVariant(PyList_GetItem(o, i)));
        }
        return list;
    }
    if (PyDict_Check(o)) {
        while (PyDict_Next(o, &i, &key, &value)) {
            map.insert(PythonScript::PythonToVariant(key).toString(), PythonScript::PythonToVariant(value));
        }
        return map;
    }
    if (PyObject_TypeCheck(o, &pyQObjectType)) {
        return QVariant::fromValue((QObject*)GET_ENCAPSULATED_C_POINTER(((pyQObject*)o)->_TWcontext));
    }
    // \TODO Complex numbers, byte arrays
    PyErr_Format(PyExc_TypeError, qPrintable(tr("the python type %s is currently not supported")), o->ob_type->tp_name);
    return QVariant();
}
Example #15
0
bool PyViewer::SetItem(int row_, int col_, const c4_Bytes &buf_) {
  const c4_Property &prop = _template.NthProperty(col_);
  c4_Row one;
  prop(one).SetData(buf_);

  PyRowRef r(one); // careful, stack-based temp
  PyObject *item = r.asPython(prop);

  if (_byPos) {
    PWOSequence item(_data[row_]);
    item[col_] = item;
  } else if (PyDict_Check((PyObject*)_data))
    PyDict_SetItemString(_data, (char*)prop.Name(), item);
  else
    PyObject_SetAttrString(_data, (char*)prop.Name(), item);

  Py_DECREF(item);
  return true;
}
Example #16
0
bool checkDictTypes(PyTypeObject* keyType, PyTypeObject* valueType, PyObject* pyIn)
{
    assert(keyType);
    assert(valueType);
    assert(pyIn);
    if (!PyDict_Check(pyIn))
        return false;

    PyObject* key;
    PyObject* value;
    Py_ssize_t pos = 0;
    while (PyDict_Next(pyIn, &pos, &key, &value)) {
        if (!PyObject_TypeCheck(key, keyType))
            return false;
        if (!PyObject_TypeCheck(value, valueType))
            return false;
    }
    return true;
}
void milxQtPythonConsole::executeCode(const QString& code)
{
    // put visible cursor to the end of the line
    QTextCursor cursor = QTextEdit::textCursor();
    cursor.movePosition(QTextCursor::End);
    setTextCursor(cursor);

    //~ int cursorPosition = this->textCursor().position();

    // evaluate the code
    _stdOut = "";
    _stdErr = "";
    PythonQtObjectPtr p;
    PyObject* dict = NULL;
    if (PyModule_Check(_context))
    {
        dict = PyModule_GetDict(_context);
    }
    else if (PyDict_Check(_context))
    {
        dict = _context;
    }
    if (dict)
    {
        p.setNewRef(PyRun_String(code.toLatin1().data(), Py_single_input, dict, dict));
    }

    if (!p)
    {
        PythonQt::self()->handleError();
    }

    flushStdOut();

    //~ bool messageInserted = (this->textCursor().position() != cursorPosition);

    //~ // If a message was inserted, then put another empty line before the command prompt
    //~ // to improve readability.
    //~ if (messageInserted) {
    //~ append(QString());
    //~ }
}
/* A variant of _PyType_Lookup that doesn't look in ProxyType.
 *
 * If argument search_wrappertype is nonzero, we can look in WrapperType.
 */
PyObject *
WrapperType_Lookup(PyTypeObject *type, PyObject *name)
{
    int i, n;
    PyObject *mro, *res, *base, *dict;

    /* Look in tp_dict of types in MRO */
    mro = type->tp_mro;

    /* If mro is NULL, the type is either not yet initialized
       by PyType_Ready(), or already cleared by type_clear().
       Either way the safest thing to do is to return NULL. */
    if (mro == NULL)
        return NULL;

    assert(PyTuple_Check(mro));

    n = PyTuple_GET_SIZE(mro)
      - 1; /* We don't want to look at the last item, which is object. */

    for (i = 0; i < n; i++) {
        base = PyTuple_GET_ITEM(mro, i);

        if (((PyTypeObject *)base) != &ProxyType) {
#if PY_MAJOR_VERSION < 3
            if (PyClass_Check(base))
                dict = ((PyClassObject *)base)->cl_dict;
            else
#endif
            {
                assert(PyType_Check(base));
                dict = ((PyTypeObject *)base)->tp_dict;
            }

            assert(dict && PyDict_Check(dict));
            res = PyDict_GetItem(dict, name);
            if (res != NULL)
                return res;
        }
    }
    return NULL;
}
Example #19
0
/*******************
 ** Video parsing **
 *******************/
static PyObject *finish_parsing(PyObject *, PyObject *args)
{
#ifdef MP_ENABLE_WEBENGINE
    PyObject *dict = NULL;
    if (!PyArg_ParseTuple(args, "O", &dict))
        return NULL;
    if (!PyDict_Check(dict))
    {
        PyErr_SetString(PyExc_TypeError, "The argument is not a dict.");
        return NULL;
    }
    QVariantHash data = PyObject_AsQVariant(dict).toHash();
    parser_webcatch->onParseFinished(data);
    Py_IncRef(Py_None);
    return Py_None;
#else
    PyErr_SetString(PyExc_RuntimeError, "The current MoonPlayer is not built with Webengine support!");
    return NULL;
#endif
}
Example #20
0
int
PyFunction_SetAnnotations(PyObject *op, PyObject *annotations)
{
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (annotations == Py_None)
        annotations = NULL;
    else if (annotations && PyDict_Check(annotations)) {
        Py_INCREF(annotations);
    }
    else {
        PyErr_SetString(PyExc_SystemError,
                        "non-dict annotations");
        return -1;
    }
    Py_XSETREF(((PyFunctionObject *)op)->func_annotations, annotations);
    return 0;
}
Example #21
0
int
PyFunction_SetKwDefaults(PyObject *op, PyObject *defaults)
{
    if (!PyFunction_Check(op)) {
        PyErr_BadInternalCall();
        return -1;
    }
    if (defaults == Py_None)
        defaults = NULL;
    else if (defaults && PyDict_Check(defaults)) {
        Py_INCREF(defaults);
    }
    else {
        PyErr_SetString(PyExc_SystemError,
                        "non-dict keyword only default args");
        return -1;
    }
    Py_XSETREF(((PyFunctionObject *)op)->func_kwdefaults, defaults);
    return 0;
}
static int Nuitka_Function_set_annotations( Nuitka_FunctionObject *object, PyObject *value )
{
    // CPython silently converts None to empty dictionary.
    if ( value == Py_None || value == NULL )
    {
        value = PyDict_New();
    }

    if (unlikely( PyDict_Check( value ) == false ))
    {
        PyErr_Format( PyExc_TypeError, "__annotations__ must be set to a dict object" );
        return -1;
    }

    PyObject *old = object->m_annotations;
    object->m_annotations = INCREASE_REFCOUNT( value );
    Py_XDECREF( old );

    return 0;
}
Example #23
0
static int
Fiber_dict_set(Fiber *self, PyObject* val, void* c)
{
    PyObject* tmp;
    UNUSED_ARG(c);

    if (val == NULL) {
        PyErr_SetString(PyExc_AttributeError, "__dict__ may not be deleted");
        return -1;
    }
    if (!PyDict_Check(val)) {
        PyErr_SetString(PyExc_TypeError, "__dict__ must be a dictionary");
        return -1;
    }
    tmp = self->dict;
    Py_INCREF(val);
    self->dict = val;
    Py_XDECREF(tmp);
    return 0;
}
Example #24
0
static int extract_params(PyObject* params_dict, plPlotterParams *params)
{
    int status=0;
	PyObject *key=NULL, *value=NULL;
    Py_ssize_t pos=0;

	if ( PyDict_Check(params_dict) ) {
		while ( PyDict_Next( params_dict, &pos, &key, &value ) ) {
            if (!set_param_from_key_value(params, key, value)) {
                goto bail;
            }
		}
        status=1;
	} else if ( params_dict != Py_None ) {
		PyErr_SetString( PyExc_TypeError, "params are not a dict" );
	}

bail:
    return status;
}
Example #25
0
static int
func_set_kwdefaults(PyFunctionObject *op, PyObject *value)
{
    PyObject *tmp;

    if (value == Py_None)
        value = NULL;
    /* Legal to del f.func_kwdefaults.
     * Can only set func_kwdefaults to NULL or a dict. */
    if (value != NULL && !PyDict_Check(value)) {
        PyErr_SetString(PyExc_TypeError,
            "__kwdefaults__ must be set to a dict object");
        return -1;
    }
    tmp = op->func_kwdefaults;
    Py_XINCREF(value);
    op->func_kwdefaults = value;
    Py_XDECREF(tmp);
    return 0;
}
Example #26
0
static PyObject *Scopeable_push(PyObject *self, PyObject *args) {
  PyObject *newDict, *dictList;
  if (!PyArg_ParseTuple(args, "OO", &self, &newDict)) {
    return NULL;
  }
  if (!PyDict_Check(newDict)) {
    PyErr_SetString(PyExc_TypeError, "push() requires a dictionary argument");
    return NULL;
  }
  dictList=PyMapping_GetItemString(((PyInstanceObject *)self)->in_dict, DICTLIST);
  if (!PyList_Check(dictList)) {
    PyErr_SetString(PyExc_TypeError, "expected list for dictList!");
    Py_XDECREF(dictList);
    return NULL;
  }
  PyList_Insert(dictList, 0, newDict); 
  Py_DECREF(dictList);
  Py_INCREF(Py_None);
  return Py_None;
}
Example #27
0
static inline void
_set_pyobj(PyObject *parent, PyObject *child, const char *key)
{
    if (child && !parent) {
        return;
    }

    if (PyList_Check(parent)) {
        PyList_Append(parent, child);
        if (child && child != Py_None) {
            Py_XDECREF(child);
        }
    }
    else if (PyDict_Check(parent)) {
        PyDict_SetItemString(parent, key, child);
        if (child && child != Py_None) {
            Py_XDECREF(child);
        }
    }
}
Example #28
0
void PyView::makeRow(c4_Row& tmp, PyObject* o, bool useDefaults) {
  for (int i=0; i < NumProperties(); i++) {
    const c4_Property& prop = NthProperty(i);
    PyObject* attr = 0;
    if (o) {
      if (PyDict_Check(o))
      {
        attr = PyDict_GetItemString(o, (char *)prop.Name());
        Py_XINCREF(attr);
      }
      else if (PySequence_Check(o))
      {
        attr = PySequence_GetItem(o, i);
      }
      else
      {
        attr = PyObject_GetAttrString(o, (char *)prop.Name());
	if (attr == 0 && i == 0 && NumProperties() == 1) 
	{
	  PyErr_Clear();
	  attr = o;
	  Py_XINCREF(attr);
	}
      }
    }
    if (attr)
    {
      try { PyRowRef::setFromPython(tmp, prop, attr); }
      catch (...) { Py_DECREF(attr); throw; }
      Py_DECREF(attr);
    }
    else {
      PyErr_Clear();
      if (useDefaults)
        PyRowRef::setDefault(tmp, prop);
    }
  }
  if (!useDefaults)
    if (tmp.Container().NumProperties() == 0)
      Fail(PyExc_ValueError, "Object has no usable attributes");
}
Example #29
0
static int 
discsim_parse_event_classes(PyObject *py_events, event_class_t *events) 
{
    int ret = -1;
    int j, size;
    double rate, u, r;
    PyObject *item, *value;
    size = PyList_Size(py_events);
    if (size == 0) {
        PyErr_SetString(DiscsimInputError, "must have > 0 events"); 
        goto out;
    }
    for (j = 0; j < size; j++) {
        item = PyList_GetItem(py_events, j);
        if (!PyDict_Check(item)) {
            PyErr_SetString(DiscsimInputError, "not a dictionary"); 
            goto out;
        }
        value = get_dict_number(item, "rate");
        if (value == NULL) {
            goto out;
        }
        rate = PyFloat_AsDouble(value);
        value = get_dict_number(item, "r");
        if (value == NULL) {
            goto out;
        }
        r = PyFloat_AsDouble(value);
        value = get_dict_number(item, "u");
        if (value == NULL) {
            goto out;
        }
        u = PyFloat_AsDouble(value);
        events[j].rate = rate;
        events[j].r = r;
        events[j].u = u;
    }
    ret = 0;
out:
    return ret;
}
Example #30
0
static PyObject *
partial_repr(partialobject *pto)
{
    PyObject *result;
    PyObject *arglist;
    PyObject *tmp;
    Py_ssize_t i, n;

    arglist = PyUnicode_FromString("");
    if (arglist == NULL) {
        return NULL;
    }
    /* Pack positional arguments */
    assert (PyTuple_Check(pto->args));
    n = PyTuple_GET_SIZE(pto->args);
    for (i = 0; i < n; i++) {
        tmp = PyUnicode_FromFormat("%U, %R", arglist,
                                   PyTuple_GET_ITEM(pto->args, i));
        Py_DECREF(arglist);
        if (tmp == NULL)
            return NULL;
        arglist = tmp;
    }
    /* Pack keyword arguments */
    assert (pto->kw == Py_None  ||  PyDict_Check(pto->kw));
    if (pto->kw != Py_None) {
        PyObject *key, *value;
        for (i = 0; PyDict_Next(pto->kw, &i, &key, &value);) {
            tmp = PyUnicode_FromFormat("%U, %U=%R", arglist,
                                       key, value);
            Py_DECREF(arglist);
            if (tmp == NULL)
                return NULL;
            arglist = tmp;
        }
    }
    result = PyUnicode_FromFormat("%s(%R%U)", Py_TYPE(pto)->tp_name,
                                  pto->fn, arglist);
    Py_DECREF(arglist);
    return result;
}