Beispiel #1
0
PyObject *
PyStructSequence_New(PyTypeObject *type)
{
    PyStructSequence *obj;
    Py_ssize_t size = REAL_SIZE_TP(type), i;

    obj = PyObject_GC_NewVar(PyStructSequence, type, size);
    if (obj == NULL)
        return NULL;
    /* Hack the size of the variable object, so invisible fields don't appear
     to Python code. */
    Py_SIZE(obj) = VISIBLE_SIZE_TP(type);
    for (i = 0; i < size; i++)
        obj->ob_item[i] = NULL;

    return (PyObject*)obj;
}
Beispiel #2
0
static PyObject *
structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
	PyObject *arg = NULL;
	PyObject *dict = NULL;
	PyObject *ob;
	PyStructSequence *res = NULL;
	Py_ssize_t len, min_len, max_len, i, n_unnamed_fields;
	static char *kwlist[] = {"sequence", "dict", 0};

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq", 
					 kwlist, &arg, &dict))
		return NULL;

	arg = PySequence_Fast(arg, "constructor requires a sequence");

	if (!arg) {				
		return NULL;
	}

	if (dict && !PyDict_Check(dict)) {
		PyErr_Format(PyExc_TypeError, 
			     "%.500s() takes a dict as second arg, if any",
			     type->tp_name);
		Py_DECREF(arg);
		return NULL;
	}

	len = PySequence_Fast_GET_SIZE(arg);
	min_len = VISIBLE_SIZE_TP(type);
	max_len = REAL_SIZE_TP(type);
	n_unnamed_fields = UNNAMED_FIELDS_TP(type);

	if (min_len != max_len) {
		if (len < min_len) {
			PyErr_Format(PyExc_TypeError, 
	       "%.500s() takes an at least %zd-sequence (%zd-sequence given)",
				     type->tp_name, min_len, len);
			Py_DECREF(arg);
			return NULL;
		}

		if (len > max_len) {
			PyErr_Format(PyExc_TypeError, 
	       "%.500s() takes an at most %zd-sequence (%zd-sequence given)",
				     type->tp_name, max_len, len);
			Py_DECREF(arg);
			return NULL;
		}
	} 
	else {
		if (len != min_len) {
			PyErr_Format(PyExc_TypeError, 
	       "%.500s() takes a %zd-sequence (%zd-sequence given)",
				     type->tp_name, min_len, len);
			Py_DECREF(arg);
			return NULL;
		}
	}

	res = (PyStructSequence*) PyStructSequence_New(type);
	if (res == NULL) {
		return NULL;
	}
	for (i = 0; i < len; ++i) {
		PyObject *v = PySequence_Fast_GET_ITEM(arg, i);
		Py_INCREF(v);
		res->ob_item[i] = v;
	}
	for (; i < max_len; ++i) {
		if (dict && (ob = PyDict_GetItemString(
			dict, type->tp_members[i-n_unnamed_fields].name))) {
		}
		else {
			ob = Py_None;
		}
		Py_INCREF(ob);
		res->ob_item[i] = ob;
	}
	
	Py_DECREF(arg);
	return (PyObject*) res;
}