1

I know you can add Writables members with:

struct PyMemberDef * PyTypeObject.tp_members

But I do not want to limit myself to a specific amount of attributes. So I created an object with __dict__ according to Andrew Floren solution: Create a Python type from C that implements a __dict__?

I can now add attributes in Python, but what if I want to add an attribute in C? How to add an attribute to an object with __dict__ in C?

PyObject with __dict __...

typedef struct {
  PyObject_HEAD
  PyObject* dict;
} BarObject;

static PyTypeObject BarObject_Type = {
  PyObject_HEAD_INIT(NULL)
};

PyMODINIT_FUNC
initFoo(void)
{
  PyObject *m;

  m = Py_InitModule("Foo", NULL);
  if (m == NULL)
    return;

  BarObject_Type.tp_new = PyType_GenericNew;
  BarObject_Type.tp_name = "Foo.Bar";
  BarObject_Type.tp_basicsize = sizeof(BarObject);
  BarObject_Type.tp_getattro = PyObject_GenericGetAttr;
  BarObject_Type.tp_setattro = PyObject_GenericSetAttr;
  BarObject_Type.tp_flags = Py_TPFLAGS_DEFAULT;
  BarObject_Type.tp_dictoffset = offsetof(BarObject,dict);
  BarObject_Type.tp_doc = "Doc string for class Bar in module Foo.";
  if (PyType_Ready(&BarObject_Type) < 0)
    return;

  Py_INCREF(&BarObject_Type);
  PyModule_AddObject(m, "Bar", (PyObject*)&BarObject_Type);
}
Community
  • 1
  • 1
Mano-Wii
  • 592
  • 5
  • 19

1 Answers1

0

Solution: Basically the dict offset must be a PyObject of type dict

BarObject *bar = PyObject_New(BarObject, &BarObject_Type);
bar->dict = PyDict_New();
PyObject_SetAttrString((PyObject*)bar, "none", Py_None);
Mano-Wii
  • 592
  • 5
  • 19
  • But for some reason the "none" does not appear in dir(bar). Why? – Mano-Wii Mar 05 '16 at 00:07
  • Please add some explanation. Imparting the underlying logic is more important than just giving the code, because it helps the OP and other readers fix this and similar issues themselves – Zulan Mar 05 '16 at 14:05