Implement EntityCollection.extend() method for Issue #27

Added extend() method to EntityCollection that accepts any iterable
of Entity objects and adds them all to the collection. The method:
- Accepts lists, tuples, generators, or any iterable
- Validates all items are Entity objects
- Sets the grid association for each added entity
- Properly handles errors and empty iterables

closes #27
This commit is contained in:
John McCardle 2025-07-03 21:05:47 -04:00
commit 1e7f5e9e7e
4 changed files with 165 additions and 1 deletions

View file

@ -637,9 +637,47 @@ PyObject* UIEntityCollection::remove(PyUIEntityCollectionObject* self, PyObject*
return Py_None;
}
PyObject* UIEntityCollection::extend(PyUIEntityCollectionObject* self, PyObject* o)
{
// Accept any iterable of Entity objects
PyObject* iterator = PyObject_GetIter(o);
if (iterator == NULL) {
PyErr_SetString(PyExc_TypeError, "UIEntityCollection.extend requires an iterable");
return NULL;
}
PyObject* item;
while ((item = PyIter_Next(iterator)) != NULL) {
// Check if item is an Entity
if (!PyObject_IsInstance(item, PyObject_GetAttrString(McRFPy_API::mcrf_module, "Entity"))) {
Py_DECREF(item);
Py_DECREF(iterator);
PyErr_SetString(PyExc_TypeError, "All items in iterable must be Entity objects");
return NULL;
}
// Add the entity to the collection
PyUIEntityObject* entity = (PyUIEntityObject*)item;
self->data->push_back(entity->data);
entity->data->grid = self->grid;
Py_DECREF(item);
}
Py_DECREF(iterator);
// Check if iteration ended due to an error
if (PyErr_Occurred()) {
return NULL;
}
Py_INCREF(Py_None);
return Py_None;
}
PyMethodDef UIEntityCollection::methods[] = {
{"append", (PyCFunction)UIEntityCollection::append, METH_O},
//{"extend", (PyCFunction)UIEntityCollection::extend, METH_O}, // TODO
{"extend", (PyCFunction)UIEntityCollection::extend, METH_O},
{"remove", (PyCFunction)UIEntityCollection::remove, METH_O},
{NULL, NULL, 0, NULL}
};

View file

@ -77,6 +77,7 @@ class UIEntityCollection {
public:
static PySequenceMethods sqmethods;
static PyObject* append(PyUIEntityCollectionObject* self, PyObject* o);
static PyObject* extend(PyUIEntityCollectionObject* self, PyObject* o);
static PyObject* remove(PyUIEntityCollectionObject* self, PyObject* o);
static PyMethodDef methods[];
static PyObject* repr(PyUIEntityCollectionObject* self);