wlav / cppyy

Other
407 stars 42 forks source link

Different behavior on cpython and pypy interpreter. #23

Open Rinoahu opened 2 years ago

Rinoahu commented 2 years ago

The following code works on cpython (I only test it on 3.7). However, it doesn't work on pypy 3:

from cppyy.gbl.std import vector as Vector
import numpy as np
from array import array

x = Vector['int'](range(10))
x = Vector['int'](np.arange(10))
x = Vector['int'](array('i', range(10)))
wlav commented 2 years ago

Yes, unfortunately, the PyPy port is behind the CPython one and several more recent features are missing in the former. (Combo of development for PyPy being harder and more folks asking for CPython.)

Rinoahu commented 1 year ago

A solution https://foss.heptapod.net/pypy/pypy/-/issues/3607

import cppyy

def pythonize_vector(klass, name):
    if 'vector<' in name:
        old_init = klass.__init__
        def pyinit(self, *args):
            if len(args) == 1:
                try:
                    iter(args[0])
                    old_init(self)
                    self. Reserve(len(args[0]))
                    self += args[0]
                    return
                except TypeError:
                    pass
            return old_init(self, *args)
        klass.__init__ = pyinit

cppyy.py.add_pythonization(pythonize_vector, 'std')