[Bf-blender-cvs] SVN commit: /data/svn/bf-blender [17680] branches/blender2.5/blender/source /blender/python/intern/bpy_rna.c: Made PyRNA props iterable, so you can do things like...

Campbell Barton ideasman42 at gmail.com
Tue Dec 2 16:27:14 CET 2008


Revision: 17680
          http://projects.blender.org/plugins/scmsvn/viewcvs.php?view=rev&root=bf-blender&revision=17680
Author:   campbellbarton
Date:     2008-12-02 16:27:10 +0100 (Tue, 02 Dec 2008)

Log Message:
-----------
Made PyRNA props iterable, so you can do things like...

for ob in bpy.objects:
	print(ob.name)

for i, lay in bpy.scenes["Scene"].layer:
	print('%d %d' % i, lay)

Modified Paths:
--------------
    branches/blender2.5/blender/source/blender/python/intern/bpy_rna.c

Modified: branches/blender2.5/blender/source/blender/python/intern/bpy_rna.c
===================================================================
--- branches/blender2.5/blender/source/blender/python/intern/bpy_rna.c	2008-12-02 14:36:35 UTC (rev 17679)
+++ branches/blender2.5/blender/source/blender/python/intern/bpy_rna.c	2008-12-02 15:27:10 UTC (rev 17680)
@@ -811,7 +811,7 @@
 {
 	PyObject *ret;
 	if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
-		PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
+		PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
 		ret = NULL;
 	} else {
 		PyObject *item;
@@ -839,7 +839,40 @@
 	return ret;
 }
 
+/* A bit of a kludge, make a list out of a collection or array,
+ * then return the lists iter function, not especially fast but convenient for now */
+PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
+{
+	/* Try get values from a collection */
+	PyObject *ret = pyrna_prop_values(self);
+	
+	if (ret==NULL) {
+		/* collection did not work, try array */
+		int len = RNA_property_array_length(&self->ptr, self->prop);
+		
+		if (len) {
+			int i;
+			PyErr_Clear();
+			ret = PyList_New(len);
+			
+			for (i=0; i < len; i++) {
+				PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
+			}
+		}
+	}
+	
+	if (ret) {
+		/* we know this is a list so no need to PyIter_Check */
+		PyObject *iter = PyObject_GetIter(ret); 
+		Py_DECREF(ret);
+		return iter;
+	}
+	
+	PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
+	return NULL;
+}
 
+
 static struct PyMethodDef pyrna_prop_methods[] = {
 	{"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
 	{"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
@@ -1027,7 +1060,7 @@
 
   /*** Added in release 2.2 ***/
 	/*   Iterators */
-	NULL,                       /* getiterfunc tp_iter; */
+	(getiterfunc)pyrna_prop_iter,	/* getiterfunc tp_iter; */
 	NULL,                       /* iternextfunc tp_iternext; */
 
   /*** Attribute descriptor and subclassing stuff ***/





More information about the Bf-blender-cvs mailing list