using the C API to access objects derived from builtin classes

Thomas Heller theller at python.net
Tue May 18 16:11:02 EDT 2004


Stefan Seefeld <seefeld at sympatico.ca> writes:

> Terry Reedy wrote:
>
>> It is easy to mess up in C ;-).  You are most likely to get an answer (from
>> another C extension writer) if you post a short as possible code snippet
>> that exhibits the error, and the actual and complete error message.
>
> I found the problem, and I'd like to share my new insight, as I don't
> think it is obvious:
>
> I hold an object reference that is a dictionary, and I modify it with
> the PyDict_* family of functions.
>
> However, the real object is not a builtin 'dict', but instead it is
> derived from it:
>
> class Dictionary(dict):
>     ...
>
> I just realized that PyDict_SetItem (et al.) don't lookup the
> methods in the object's __dict__, so the method that gets really
> executed is not the overloaded I wrote, but the method from the
> base class.
>
> Replacing 'PyDict_SetItem' by 'PyObject_SetItem' did the trick.
> I guess 'PyDict_SetItem' is a shortcut to circumvent the lengthy
> method lookup. Fair enough, but the python C API documentation could
> be a bit more clear about that...

I would guess the *real* problem is that you are ignoring the return
value of PyDict_SetItem (or whatever api you use).  In this case you get
weird errors afterwards.

Thomas





More information about the Python-list mailing list