1

Targeting Python 3.7+, how can one return a new class instance to Python code from a C extension?

Dictionaries, lists, tuples are easy (example of the latter): return Py_BuildValue("(OO)", Py_False, Py_None);

This truly ancient thread (https://grokbase.com/t/python/python-list/99ack91fye/creating-python-class-instances-from-c-api) highlights PyInstance_New(). Which appears long since removed from the API.

Ideally there would be something like Py_BuildClass("s{{s:s},{s,i}}","Dog","name","fido","age",11);

Any thoughts welcomed.

P.S. Ideally not constructable from Python code. But that'd be icing on the cake.

P.P.S. To clarify. Assume the extension (call it Kennel) manages a Dog class:

struct Dog
{
    char* name;
    int age;
};

and my Python extension has a function which returns a Dog instance to a Python consumer. It would be good to be able to do this:

dog = kennel.getDog()
print(f"{dog.name} is {dog.age}")
J Evans
  • 1,090
  • 2
  • 16
  • 36
  • Possible duplicate of https://stackoverflow.com/questions/4163018/create-an-object-using-pythons-c-api . Short answer: you call the class, same as in Python – user253751 Nov 26 '20 at 19:24
  • @user253751 OK, upon re-reading, not quite the question I was asking. I am not returning an instance of the extension type, but a new class. Think of it as a C function that returns a struct. Please see my P.P.S. – J Evans Nov 26 '20 at 19:30
  • You want to return a whole new class every time? Not just a new instance of a class? – user253751 Nov 26 '20 at 19:39
  • ideally yes. am open to any other suggestions. – J Evans Nov 26 '20 at 19:42
  • why can't you just define the class once, and return a new instance each time? which you do like this: https://docs.python.org/3/extending/newtypes_tutorial.html – user253751 Nov 26 '20 at 19:45
  • looking for [`Py_BuildValue`](https://docs.python.org/3/c-api/arg.html#building-values)? – Thomas Nov 26 '20 at 19:50
  • @Thomas - thanks. am 100% down with `Py_BuildValue()`. Please see second paragraph of my question. What I'm asking is is there something similar to create a Python class instance? Not a tuple or dictionary. Thx. – J Evans Nov 26 '20 at 19:52
  • sure, the other way is what user253751 suggested, defining a type and returning instances of that type. if you don't want to do it yourself, use some wrapper generating tooling like [SWIG](http://www.swig.org/) or [PyAutoC](https://github.com/orangeduck/PyAutoC) – Thomas Nov 26 '20 at 20:05

0 Answers0