Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create instance of a python class , declared in python, with C API

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

like image 911
Paul Avatar asked Jul 18 '09 12:07

Paul


People also ask

How do you create an instance of a class in a class Python?

To create instances of a class, you call the class using class name and pass in whatever arguments its __init__ method accepts.

What is an instance of a class Python?

Instance is an object that belongs to a class. For instance, list is a class in Python. When we create a list, we have an instance of the list class.

What does __ init __ do in Python?

The __init__ method is the Python equivalent of the C++ constructor in an object-oriented approach. The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose. It is only used within classes.


1 Answers

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.

like image 159
Alex Martelli Avatar answered Sep 22 '22 10:09

Alex Martelli