Having poked around a little bit, I found there doesn't appear to be any way to get at the contents of a cell object from Python. It's not the sort of thing that one needs to be doing very frequently, but I've run into a few situations recently where it would be really useful from a debugging standpoint.
You can get at a cell object containing a given value by making a quick closure and looking at the func_closure attribute: (lambda x: lambda: x)(some_value).func_closure[0] but there's not anything we can easily do with that object to find out what it's pointing at. The str() representation helpfully tells us the id of the contained value, but I'm not aware of a way to get at an object given its id [1]. So I thought it might be useful to add such a method to the cell object type. Attached is a sample patch that does so (against python2.4). Does this look like the sort of thing that would be useful to anyone else? How does one go about getting small changes like this into Python anyway? -- paul [1] Yes, the id is the object's pointer in cPython, but even I don't think it would be a good idea to allow accessing an object via the id, even if it's possible. :)
diff -Naur python2.4-2.4dfsg/Objects/cellobject.c python2.4-2.4dfsg-pik2/Objects/cellobject.c --- python2.4-2.4dfsg/Objects/cellobject.c 2001-08-29 17:51:00.000000000 -0600 +++ python2.4-2.4dfsg-pik2/Objects/cellobject.c 2005-03-15 14:21:02.389725784 -0700 @@ -86,6 +86,13 @@ return 0; } +static PyMethodDef cell_methods[] = { + {"value", (PyCFunction)PyCell_Get, METH_NOARGS, + "Return the value stored by the cell" + }, + {NULL} /* sentinel */ +}; + PyTypeObject PyCell_Type = { PyObject_HEAD_INIT(&PyType_Type) 0, @@ -111,4 +118,9 @@ 0, /* tp_doc */ (traverseproc)cell_traverse, /* tp_traverse */ (inquiry)cell_clear, /* tp_clear */ + 0, /* tp_richcompare */ + 0, /* tp_weaklistoffset */ + 0, /* tp_iter */ + 0, /* tp_iternext */ + cell_methods, /* tp_methods */ };
-- http://mail.python.org/mailman/listinfo/python-list