using the C API to access objects derived from builtin classes

Thomas Heller theller at python.net
Wed May 19 02:32:40 EDT 2004


Stefan Seefeld <seefeld at sympatico.ca> writes:

> Thomas Heller wrote:
>
>>>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.
>
> good shot ! Well, what the 'real' problem is is probably a matter
> of perspective, but you are quite right in that I failed to check
> a return value (and associated exception) so python's own code
> eventually bumped into it in an unrelated context.

And that will always catch you!

> But back to the other issue: isn't there any text that explains
> when I should be using PyDict_GetItem and when PyObject_GetItem
> and what they are doing byhind the scene ?

The PyObject_GetItem() function belongs to the Abstract Objects Layer.
<http://docs.python.org/api/abstract.html>
The docs say:

  6. Abstract Objects Layer

  The functions in this chapter interact with Python objects regardless
  of their type, or with wide classes of object types (e.g. all
  numerical types, or all sequence types). When used on object types for
  which they do not apply, they will raise a Python exception.

while PyDict_GetItem() belongs to the Concrete Objects Layer for
PyDictObject <types http://docs.python.org/api/concrete.html>:

  7. Concrete Objects Layer 

  The functions in this chapter are specific to certain Python object
  types. Passing them an object of the wrong type is not a good idea; if
  you receive an object from a Python program and you are not sure that
  it has the right type, you must perform a type check first; for
  example, to check that an object is a dictionary, use
  PyDict_Check(). The chapter is structured like the ``family tree'' of
  Python object types.

Reading the include files may also help - once you get the idea it's simple.

Thomas





More information about the Python-list mailing list