Home > Back-end >  Python C API make member private
Python C API make member private

Time:12-02

I'm making a python extension module using my C code and I've made a struct that I use to pass my C variables. I want some of those variables to be inaccessible from the python level. How can I do that?

    typedef struct {
        PyObject_HEAD
        std::string region;
        std::string stream;

        bool m_is_surface = false;
        bool m_is_stream = false;
    } PyType;

I want m_is_surface and m_is_stream to be inaccessible by the user. Only PyType's methods should access it. So the and user CAN'T do something like this:

import my_module

instance = my_module.PyType()
instance.m_is_surface = False # This should raise an error. Or preferably the user can't see this at all

I cannot just add private to the struct because python type members are created as a standalone function and is linked to the type later on, so I cannot access them inside the struct's methods. So if I say:


 int PyType_init(PyType *self, PyObject *args, PyObject *kwds)
    {
        static char *kwlist[] = {"thread", "region", "stream", NULL};
        PyObject *tmp;


        if (!PyArg_ParseTupleAndKeywords(args, kwds, "bs|s", kwlist,
                                        &self->thread, &self->region, &self->stream))
            return -1;
        
        return 0;
    }

It will raise an is private within this context error.

CodePudding user response:

You should do nothing. Unless you create an accessor property these attributes are already inaccessible from Python. Python cannot automatically see C/C struct members.

  • Related