PyCheck for a classes defined in python and user data in PyObject_HEAD

Hrvoje Niksic hniksic at xemacs.org
Fri Nov 2 10:45:23 CET 2007


Note that there is a mailing list dedicated to the Python/C API,
http://mail.python.org/mailman/listinfo/capi-sig

sndive at gmail.com writes:
> issue #2 I'm in a situation when i don't really need to extend
> python with any classes of my own but i do have extra luggage for
> the python data structures such as tuples, lists, dictionaries, etc
> on the c++ side. I see no place in PyObject_HEAD where i can stick a
> void* to my extra data.

Adding additional luggage is a valid definition of extending.  :-)

Simply inherit from the desired data structure, and add the pointers
you need to the extended structure.  If you must add extra data to
existing Python objects created by someone else, then you can use a
weak dictionary:

import weakref
_map = {}  # can't use WeakKeyDictionary because we need
           # mapping by identity

def set_extra_data(obj, data):
    # use id(obj) as key to map by object identity
    ident = id(obj)
    ref = weakref.ref(obj, lambda x: _map.pop(ident))
    _map[ident] = ref, data

def extra_data(obj):
    if id(obj) not in _map:
        raise TypeError("object has no extra data")
    ref, data = _map[id(obj)]
    assert ref() is obj
    return data



More information about the Python-list mailing list