[capi-sig] Creating type object dynamically in run-time

Stefan Behnel python_capi at behnel.de
Thu May 10 18:32:04 CEST 2012


Mateusz Loskot, 10.05.2012 15:55:
> On 10 May 2012 14:01, Stefan Behnel wrote:
>> Note that this is even easier in Cython, where you write Python code anyway
>> (instead of C code).
> 
> Yes, I looked at the Cython docs.
> Unfortunately, I can't use it. I have to stick to Python 3.2 dist.

Cython works perfectly with Py3.2, even with the latest 3.3-pre and Python
2.4 and later as well. Helps you write portable code.


>>> However, I'd really like to learn canonical means of generating extension types
>>> dynamically using plain Python C API.
>>> Long story short, I assume I'm looking for Python C API equivalent of
>>> using type() function.
>>
>> Then call type().
> 
> It's possible, certainly.
> But, is there any plain C equivalent, perhaps using PyType_Type
> and the Descriptor Objects?
> (Why purpose and usage of the Descriptor Objects are not documented?.)
> I'm seeking for confirmation, if such approach would be close to the
> type() function.
> 
> To summary:
> 
> 1)
> It seems to be that generating script with Python classes in textual form
> and then using Python C API like PyRun_StringFlags, etc.
> is the recommended approach

It's certainly much easier than doing everything in C.


> 2)
> There is approach based on direct call to type() function
> using Python C API.
> 
> 3)
> Is there third option possible which replaces the 2nd's type() call
> with chain of plain Python C API calls?
> I know there are pros/cons related to amount of code, maintenance hassle,
> code complexity, and such. but it is not related to my question really.

I don't know what the best way is here. However, I really wonder what you
are trying to achieve. If I was to implement an interface for an embedded
Python runtime, I'd much rather focus on the design of the user level API
that I'm exposing than the details of the low-level interface
implementation. (But then again, I'd leave those mostly to Cython, so if
you prefer doing them yourself, you'll have to jump through some more
hoops, obviously.)

Stefan


More information about the capi-sig mailing list