[Python-checkins] CVS: python/dist/src/Objects object.c,2.148,2.149

Tim Peters tim_one@users.sourceforge.net
Sun, 16 Sep 2001 19:38:48 -0700


Update of /cvsroot/python/python/dist/src/Objects
In directory usw-pr-cvs1:/tmp/cvs-serv31213/python/Objects

Modified Files:
	object.c 
Log Message:
PyObject_Dir():  Merge in __members__ and __methods__ too (if they exist,
and are lists, and then just the string elements (if any)).

There are good and bad reasons for this.  The good reason is to support
dir() "like before" on objects of extension types that haven't migrated
to the class introspection API yet.  The bad reason is that Python's own
method objects are such a type, and this is the quickest way to get their
im_self etc attrs to "show up" via dir().  It looks much messier to move
them to the new scheme, as their current getattr implementation presents
a view of their attrs that's a untion of their own attrs plus their
im_func's attrs.  In particular, methodobject.__dict__ actually returns
methodobject.im_func.__dict__, and if that's important to preserve it
doesn't seem to fit the class introspection model at all.


Index: object.c
===================================================================
RCS file: /cvsroot/python/python/dist/src/Objects/object.c,v
retrieving revision 2.148
retrieving revision 2.149
diff -C2 -d -r2.148 -r2.149
*** object.c	2001/09/16 20:33:22	2.148
--- object.c	2001/09/17 02:38:46	2.149
***************
*** 1418,1421 ****
--- 1418,1458 ----
  }
  
+ /* Helper for PyObject_Dir.
+    If obj has an attr named attrname that's a list, merge its string
+    elements into keys of dict.
+    Return 0 on success, -1 on error.  Errors due to not finding the attr,
+    or the attr not being a list, are suppressed.
+ */
+ 
+ static int
+ merge_list_attr(PyObject* dict, PyObject* obj, char *attrname)
+ {
+ 	PyObject *list;
+ 	int result = 0;
+ 
+ 	assert(PyDict_Check(dict));
+ 	assert(obj);
+ 	assert(attrname);
+ 
+ 	list = PyObject_GetAttrString(obj, attrname);
+ 	if (list == NULL)
+ 		PyErr_Clear();
+ 
+ 	else if (PyList_Check(list)) {
+ 		int i;
+ 		for (i = 0; i < PyList_GET_SIZE(list); ++i) {
+ 			PyObject *item = PyList_GET_ITEM(list, i);
+ 			if (PyString_Check(item)) {
+ 				result = PyDict_SetItem(dict, item, Py_None);
+ 				if (result < 0)
+ 					break;
+ 			}
+ 		}
+ 	}
+ 
+ 	Py_XDECREF(list);
+ 	return result;
+ }
+ 
  /* Like __builtin__.dir(arg).  See bltinmodule.c's builtin_dir for the
     docstring, which should be kept in synch with this implementation. */
***************
*** 1483,1486 ****
--- 1520,1531 ----
  		}
  		if (masterdict == NULL)
+ 			goto error;
+ 
+ 		/* Merge in __members__ and __methods__ (if any).
+ 		   XXX Would like this to go away someday; for now, it's
+ 		   XXX needed to get at im_self etc of method objects. */
+ 		if (merge_list_attr(masterdict, arg, "__members__") < 0)
+ 			goto error;
+ 		if (merge_list_attr(masterdict, arg, "__methods__") < 0)
  			goto error;