[Python-Dev] Possible low-hanging optimization (original) (raw)

Guido van Rossum guido@python.org
Thu, 12 Dec 2002 13:07:45 -0500


In Boost.Python, extension class instance dictionaries are created only on-demand. It's an obvious win for lots of wrapped C++ class instances, which will never have Python attributes tacked on. This also seems like a potential big win for some kinds of Python instances, like those which use slots but may also have a dictionary (IIRC that is a possible configuration). The code to do this in Boost.Python is small and "just works" transparently, so I thought there might be some interest here for the Python core:

I've "C-ified" the code here, sort of on-the-fly, just to give an idea, but it's so simple that any errors can't obscure the intent /too/ much ;-) static PyObject* instancegetdict(PyObject* op, void*) { bplinstance* inst = (bplinstance*)op; if (inst->dict == 0) inst->dict = PyDictNew(); PyXINCREF(inst->dict); return inst->dict; } static int instancesetdict(PyObject* op, PyObject* dict, void*) { (bplinstance)* inst = (bplinstance*)op; PyXDECREF(inst->dict); PyXINCREF(dict); inst->dict = dict return 0; } static PyGetSetDef instancegetsets[] = { /* used as tpgetset */ {"dict", instancegetdict, instancesetdict, NULL}, {0} }; Useful?

AFAICT, this is already done for new-style classes. For classic classes, it would be too much of a break with history.

--Guido van Rossum (home page: http://www.python.org/~guido/)