defines or C vars visible to python?

Fredrik Lundh effbot at
Sat Mar 4 15:40:10 CET 2000

Tom Morton wrote:
> I'm writing a small colour ncurses module (in C) for a python project of
> I've had no real trouble apart from one point: Various colours are defined
> the module as:
> #define COL_RED 1
> etc.
> Is there any way I can make these visible to python when the module is
> imported, so instead of using numbers I can do this:
> cursesmod.changecol(COL_RED)
> instead of:
> cursesmod.changecol(1)
> I've probaby missed something in the Python/C api docs but it's driving me
> insane!

just add them to the module dictionary:

static void
setint(PyObject *d, char* name, int value)
    PyObject *v = PyInt_FromLong(value);
    if (!v || PyDict_SetItemString(d, name, v))
        PyErr_Clear(); /* just ignore errors */

    PyObject* m;
    PyObject* d;

    m = Py_InitModule("mymodule", myfunctions);
    d = PyModule_GetDict(m);

    setint(d, "MY_CONSTANT", MY_CONSTANT);
    /* etc */

hope this helps!


<!-- (the eff-bot guide to) the standard python library:

More information about the Python-list mailing list