[Cython] Automatic C++ conversions

Stefan Behnel stefan_ml at behnel.de
Thu Jun 28 14:10:07 CEST 2012


Robert Bradshaw, 28.06.2012 12:07:
> On Thu, Jun 28, 2012 at 2:54 AM, Stefan Behnel wrote:
>> Robert Bradshaw, 28.06.2012 10:59:
>>> I've been looking how painful it is to constantly convert between
>>> Python objects and string in C++.
>>
>> You mean std::string (as I think it's called)? Can't we just special case
>> that in the same way that we special case char* and friends?
> 
> Yes, we could.

Then I think it makes sense to do that. Basically, the std::string type
would set its is_string flag and then we need the actual coercion code for it.


> If we do that it'd make sense to special case list and
> vector and pair and and map and set as well, though perhaps those are
> special enough to hard code them, and it makes the language simpler to
> not have more special methods.

Ok, then it's

std::string <=> bytes
std::vector <=> list
std::map <=> dict
std::set <=> set

Potentially also:

std::pair => tuple (maybe 2-tuple => std::pair with a runtime length test?)

What about allowing list(<C++ iterator>) etc.? As long as the item type can
be coerced at compile time, this should be doable:

<C++ iterator> => Python iterator

and it would even be easy to implement in Cython code using a generator
function. The other direction (Python iterator => <C++ iterator>) would be
trickier but could also be made to work when the C++ item type on the LHS
of the assignment that triggers the coercion is known at compile time.

We might want to look for a way to make these coercions a "thing" in the
code (maybe through a registry or dedicated class) rather than adding
special casing code everywhere.

I think a CEP would be a good way to specify the above coercions.

I also think that this is large enough a feature to openly ask for sponsorship.


>> Basically just
>> one type more in that list. And it would give you efficient
>> encoding/decoding more or less for free.
>>
>> I mean, well, it would likely break existing code to start doing that (in
>> the same way that we broke code by enabling type inference for convertible
>> pointers), but as long as it helps more than it breaks ...
> 
> I don't think it'd be backwards compatible, currently it's just an error.

Ah, right, sorry. I got confused. Assignments to an untyped variable
inherit the type of the RHS, so only typed assignments would be impacted,
and those are currently errors, sure. Nothing in the way then.

Stefan


More information about the cython-devel mailing list