extending the built in dictionary type

Robin Becker robin at jessikat.fsnet.co.uk
Fri Mar 23 03:15:15 EST 2001


In article <6Rzu6.12951$_46.485491 at e420r-atl2.usenetserver.com>, Steve
Holden <sholden at holdenweb.com> writes
>"Robin Becker" <robin at jessikat.fsnet.co.uk> wrote in message
>news:umfKujAz2iu6EwHa at jessikat.demon.co.uk...
>> I'm interested in extending the built in dictionary. It's fairly simple
>> to wrap, but seems incredibly hard to chain the methods. Is there any
>> obvious way to use most of the built in methods whilst modifying a few.
>>
>> Seems that although it exists I can't chain the original mapp_methods of
>> dictobject as that is not visible outside pythonxx.dll. So is there an
>> easier way to get at these internal types?
>
>See FAQ 5.18: How do I define and create objects corresponding to
>built-in/extension types?
>
>regards
> Steve
perhaps I didn't make myself clear. I will use UserDict for a python
version, but if I want to accelerate to C I find fundamental problems in
getting useful access to the code of say dictobject; in particular
there's no obvious way to extend/modify in a small way; eg have a dict
with just one more method. I either have to just copy that code
wholesale or do rather silly things like changing my object's type
before and after the operation. As an example I'm forced to do this to
safely wrap d[x] and d[x]=v

static PyObject * MYDict_subscript(PyObject *self, register PyObject
*key)
{
        PyObject* r;
        self->ob_type=&PyDict_Type;
        r = dict_subscript(self,key);
        self->ob_type=&MyDictType;
        return r;
}

static int MyDict_ass_sub(PyObject *self, PyObject *v, PyObject *w)
{
        int r;
        self->ob_type=&PyDict_Type;
        r = dict_ass_sub(self,v,w);
        self->ob_type=&MyDictType;
        return r;
}

this because the internal methods dict_subscript, dict_ass_sub do type
checking which is a bit peculiar as I would expect the internal methods
to assume the correct type.

Worse I find that there's no standard way to get at or the chain of
methods for the built in types. Some lip service stuff is there in the
chain methods, but no way to get at the chain except by using some
rather dubious coding eg

        v = PyObject_GetAttrString(d,"has_key");
        dmapp_methods = (PyMethodDef*)(((PyCFunctionObject*)v)->m_ml);

"has_key" is the name of the first thing on the list and that could
change. So I can use this sneakiness to get at and build a chain. My
objects now work pretty much as expected; provided I wrap those methods
of dictobject which do PyDict_Check(). The "__methods__" special is
treated wrongly in that some methods appear twice in the list, but
that's a minor issue as the callchain is handled correctly.
-- 
Robin Becker



More information about the Python-list mailing list