9

How would one expose "static" variables like this

class MyClass:
    X = 1
    Y = 2

via the C API? The only variable on the PyTypeObject that looks like it would work is tp_members, but I see no flag in the PyMemberDef to indicate that the member should be per-class, not per-instance.

For a bit more clarification, since it may change the answer, I'm trying to expose a C enum to Python such that the enumeration

enum MyFlags {
    Alpha = 0,
    Beta = 1
};

Can be accessed in Python as:

module.MyFlags.Alpha
module.MyFlags.Beta
1
  • I only found this SO question after I had figured out the answer myself. Prior to that I searched for things like "cpython class constants". I wonder if we could add more words to this question that could help other people find this. Commented Dec 1, 2021 at 5:57

1 Answer 1

12

Just put them in the type's tp_dict e.g. with PyDict_SetItemString.

Sign up to request clarification or add additional context in comments.

4 Comments

Excellent! That's what I was looking for. (You'll excuse me if I take a moment to test it out before marking this as answered.)
Works as advertised. :) Thanks again.
Since the time this answer was originally posted, the following warning has been added to the docs: "Warning: It is not safe to use PyDict_SetItem() on or otherwise modify tp_dict with the dictionary C-API."
I think that warning is a bit broader than it should be - it should be okay to set entries in tp_dict as long as the names don't have any corresponding slots (so no setting __add__ or __new__ or stuff like that) and you call PyType_Modified on the type afterward.

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.