8

I want to do the equivalent of

class Foo(object):
  bar = 1

using Python's C API. In other words, I want to create a Python class which has a static variable, using C.

How can I do this?

2 Answers 2

5

Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:

PyTypeObject type;
// ...other initialisation...
type.tp_dict = PyDict_New();
PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1));
Sign up to request clarification or add additional context in comments.

Comments

2

You can pass that source code to Py_CompileString with the appropriate flags.

If you already have the class you could use PyObject_SetAttr.

3 Comments

Thanks for the suggestion! It seems a bit of a roundabout way to do it though - is there anything similar to PyModule_AddIntConstant for classes?
Sorry, I only just noticed that you updated your answer. Thanks again for the help. I've tried using PyObject_SetAttr, but no matter when I call it I get a TypeError with the message "can't set attributes of built-in/extension type X" (where X is my type name). Am I doing something wrong, or does this simply not work with type objects?
I found the solution I was after in the end. Thanks a lot for your suggestions though!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.