9

I want to create an instance of a Python class defined in the __main__ scope with the C API.

For example, the class is called MyClass and is defined as follows:

class MyClass:
    def __init__(self):
        pass

The class type lives under __main__ scope.

Within the C application, I want to create an instance of this class. This could have been simply possible with PyInstance_New as it takes class name. However this function is not available in Python3.

Any help or suggestions for alternatives are appreciated.

Thanks, Paul

ArtOfWarfare
  • 20,617
  • 19
  • 137
  • 193
Paul
  • 2,474
  • 7
  • 33
  • 48

1 Answers1

20

I believe the simplest approach is:

/* get sys.modules dict */
PyObject* sys_mod_dict = PyImport_GetModuleDict();
/* get the __main__ module object */
PyObject* main_mod = PyMapping_GetItemString(sys_mod_dict, "__main__");
/* call the class inside the __main__ module */
PyObject* instance = PyObject_CallMethod(main_mod, "MyClass", "");

plus of course error checking. You need only DECREF instance when you're done with it, the other two are borrowed references.

denfromufa
  • 5,610
  • 13
  • 81
  • 138
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395