How do I create a vanilla object in C?

Carl Banks pavlovevidence at
Sun Nov 22 04:05:30 CET 2009

On Nov 21, 12:49 pm, rnich... at wrote:
> I need to create a vanilla object in C, something I can do
> PyObject_SetAttr on.  Obviously, I do something somewhat like this every
> time I create a minimal python class.  I need to know how to do this in C
> though.

First of all, if you don't need to share this object with any Python
code, then I'd suggest you just use a dict (create with PyDict_New).

If you do need to share it with Python, one thing to consider is
whether it isn't easier to create the object in Python and pass it to
the C code.

If these suggestions aren't suitable, then you'll have to create a new
vanilla type, then create an instance of that type.  Unfortunately
it's not too convenient from C.  It's easy enough to define types and
C (see the C-API documentation), but in order to use PyObject_SetAttr
on it you'll have to make sure the type has a dictionary, so you'd
have to set the tp_dictoffset member to the offset of your dict in the
Python structure.

Another thing you can do is to call type directly (as you can do in
Python) with the name, bases, dict, as in the following example (error
checking and reference counting omitted):

name = PyString_FromString("vanilla");
bases = PyTuple_New(0);
dict = PyDict_New();
vanilla_type = PyObject_CallObject(

Then call the vanilla type (however you create it) to get a vanilla

vanilla_object = PyObject_CallObject(vanilla_type,0);

Definitely not the most straightforward thing to do from C.

Carl Banks

More information about the Python-list mailing list