Manipulating sets from the 2.4 C API?

Raymond Hettinger python at rcn.com
Tue Apr 11 14:47:19 EDT 2006


Dave Opstad wrote:
> I just looked through the Python/C API reference for 2.4.3 and didn't
> see anything about using sets. I'd been expecting things like PySet_New,
> PySet_Check etc.

In Py2.4, there was not a custom set C API because the module was still
ungoing significant development.  For 2.4, the best way to access sets
from C is to use the abstract API:

s=PyObject_CallObject(PySet_Type, NULL)        // s=set()
PyObject_TypeCheck(o, &PySet_Type)             // isinstance(o, set)
PyObject_GetIter(s)                            // iter(s)
PyObject_Hash(f)                               // hash of frozenset
PyObject_Length(s)                             // len(s)
PyNumber_Subtract(s,t)                         // s - t
PyObject_CallMethod(s, "pop", NULL)            // s.pop()


> If I want to handle sets should I just use a dictionary's keys and
> ignore the values, or is there some more explicit set support somewhere
> I'm not seeing?

In Py2.4, set objects are based on dictionaries so the performance is
about the same, so the only advantage of using set objects instead of
dictionaries is that they provide methods like union, intersection, etc
which are not defined for dictionaries.

In Py2.5, set objects are no longer based on dictionaries and tend to
have better speed/space performance than equivalent dictionary code.
There is also a more full-blown C API including PySet_New(),
PySet_Size(), PySet_Add(), PySet_Contains(), ...




More information about the Python-list mailing list