Commit 6f9a0b21 authored by Guido van Rossum's avatar Guido van Rossum

New dir() function --

- uses abstract interface where possible
- uses __members__ and __methods__
- returns [] when an object has no info available
parent 439aae95
...@@ -384,39 +384,65 @@ builtin_dir(self, args) ...@@ -384,39 +384,65 @@ builtin_dir(self, args)
PyObject *self; PyObject *self;
PyObject *args; PyObject *args;
{ {
PyObject *v = NULL; static char *attrlist[] = {"__members__", "__methods__", NULL};
PyObject *d; PyObject *v = NULL, *l = NULL, *m = NULL;
PyObject *d, *x;
int i;
char **s;
if (!PyArg_ParseTuple(args, "|O:dir", &v)) if (!PyArg_ParseTuple(args, "|O:dir", &v))
return NULL; return NULL;
if (v == NULL) { if (v == NULL) {
d = PyEval_GetLocals(); x = PyEval_GetLocals();
Py_INCREF(d); if (x == NULL)
goto error;
l = PyMapping_Keys(x);
if (l == NULL)
goto error;
} }
else { else {
d = PyObject_GetAttrString(v, "__dict__"); d = PyObject_GetAttrString(v, "__dict__");
if (d == NULL) { if (d == NULL)
PyErr_SetString(PyExc_TypeError, PyErr_Clear();
"dir() argument must have __dict__ attribute"); else {
return NULL; l = PyMapping_Keys(d);
} if (l == NULL)
PyErr_Clear();
Py_DECREF(d);
} }
if (PyDict_Check(d)) { if (l == NULL) {
v = PyDict_Keys(d); l = PyList_New(0);
if (PyList_Sort(v) != 0) { if (l == NULL)
Py_DECREF(v); goto error;
v = NULL;
} }
for (s = attrlist; *s != NULL; s++) {
m = PyObject_GetAttrString(v, *s);
if (m == NULL) {
PyErr_Clear();
continue;
} }
else { for (i = 0; ; i++) {
v = PyObject_CallMethod(d, "keys", NULL); x = PySequence_GetItem(m, i);
if (v == NULL) { if (x == NULL) {
PyErr_Clear(); PyErr_Clear();
v = PyList_New(0); break;
} }
if (PyList_Append(l, x) != 0) {
Py_DECREF(x);
Py_DECREF(m);
goto error;
} }
Py_DECREF(d); Py_DECREF(x);
return v; }
Py_DECREF(m);
}
}
if (PyList_Sort(l) != 0)
goto error;
return l;
error:
Py_XDECREF(l);
return NULL;
} }
static PyObject * static PyObject *
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment