[capi-sig] Python to Scheme type conversion in C?
stefan_ml at behnel.de
Mon May 31 23:12:52 CEST 2010
Jason Baker, 31.05.2010 22:31:
> On Mon, May 31, 2010 at 3:06 PM, Stefan Behnel wrote:
>> Jason Baker, 31.05.2010 21:45:
>>> On Mon, May 31, 2010 at 2:05 PM, Stefan Behnel wrote:
>>>> Jason Baker, 31.05.2010 18:15:
>>>>> I'm looking for a way to convert Python objects into Scheme values.
>>>>> Essentially what I'm trying to do is say "Is this a Python integer?
>>>>> Ok, convert it to a Scheme integer." or "Is this a Python string?
>>>>> Ok, convert it into a Scheme string." ... etc.
>>>>> What is the best way to do this? My first intuition was to call
>>>>> Py*_Check to determine the type, but it turns out that's a macro that
>>>>> can't be used in non-c code. I'm sure I could translate that into the
>>>>> appropriate C code, but that gives me a bad feeling.
>>>> Those are macros because that makes them really, really fast, especially
>>>> Py3. However, their definition changes between Python versions, so
>>>> them by regular C code is really not a good idea.
>>>> In general, I wouldn't try to make the wrapper too generic. You might
>>>> to inspect the underlying Scheme code (potentially at runtime), and infer
>>>> the possible types (or the required conversion) from that.
>>> Perhaps I should clarify. For now, I'm just trying to embed the python
>>> interpreter in Scheme. Thus, I know what types the scheme values are,
>>> and I know how to translate them into the appropriate Python values.
>>> What I'm trying to figure out is how to go the other way. That is,
>>> how do I figure out what type a PyObject is so I know how to create
>>> the appropriate Scheme value?
>> Why not write a type checking cascade in plain C or Cython?
> I suppose I could, but I'd rather write it in pure Scheme or Python if
> at all possible. If that's not efficient enough, I can look into
> adding C into the mix.
You could build a dict that maps any combination of a builtin Python type
and a Scheme type to a way to convert the first to the second. That might
even be faster than a type checking cascade in C. Structured types would
fall back to the standard Python type conversion rules.
More information about the capi-sig