[Python-Dev] Possible low-hanging optimization
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* instance_get_dict(PyObject* op, void*)
> {
> bpl_instance* inst = (bpl_instance*)op;
> if (inst->dict == 0)
> inst->dict = PyDict_New();
> Py_XINCREF(inst->dict);
> return inst->dict;
> }
>
> static int instance_set_dict(PyObject* op, PyObject* dict, void*)
> {
> (bpl_instance)* inst = (bpl_instance*)op;
> Py_XDECREF(inst->dict);
> Py_XINCREF(dict);
> inst->dict = dict
> return 0;
> }
>
> static PyGetSetDef instance_getsets[] = { /* used as tp_getset */
> {"__dict__", instance_get_dict, instance_set_dict, 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/)