1 year ago

#365667

test-img

Mansoor

TypeError when running Cython compiled regular Python class

My Python code runs fine when interpreted, but when I Cython compile it without making any changes, I get a runtime TypeError:

  File "myClass.pyx", line X, in myClass.default_fac
TypeError: wrap() takes exactly one argument (0 given)

I'm not sure how to interpret this error, there is no wrap() function in my code or the generated C code. I have abbreviated the relevant code below:

class basic_class:
    obj_1: int
    obj_2: int

    def __init__(self, obj_1, obj_2):
        self.obj_1 = obj_1
        self.obj_2 = obj_2

    def __add__(self, rhs_obj_2: int):
        return basic_class(
            obj_1=self.obj_1,
            obj_2=self.obj_2 + rhs_obj_2,
        )

class myClass:
    def __init__(
        self,
        id_generator: Callable):
        self.id_generator = id_generator # random number generator
        self.basic_class_dict = self._new_basic_class_dict({})

    def default_fac(self) -> basic_class:
        return basic_class(obj_1=self.id_generator(), obj_2=0)

    def _new_basic_class_dict(self, existing_basic_class_dict) -> Dict[int, basic_class]:
        return defaultdict(self.default_fac, existing_basic_class_dict)

    def some_random_method(self):
        # ... 
        
        self.basic_class_dict = self._new_basic_class_dict(
            {
                key: self.basic_class_dict[some_index] + len(value)
                for key, value in input_data_dict.items()
            }
        )

Seems like passing the default_fac method as an argument to the defaultdict constructor is tripping Cython up?


Building my code with Poetry, I've listed my build.py below:

import os

try:
    # Test for cython
    from Cython.Build import cythonize

except ImportError:
    # Provide empty build func if not available
    def build(setup_kwargs):
        pass


else:
    from setuptools import Extension  # noqa
    from setuptools.dist import Distribution  # noqa
    from distutils.command.build_ext import build_ext

    # This function will be executed in the implicit setup.py:
    def build(setup_kwargs):

        extensions = [
            "myClass.pyx",  # noqa
        ]

        #os.environ["CC"] = "gcc-9.4.0"  # noqa
        os.environ["CFLAGS"] = "-O3 -ffast-math -march=native -fopenmp"  # noqa

        setup_kwargs.update(
            {
                "ext_modules": cythonize(
                    extensions,
                    language_level=3,
                    nthreads=2,
                    compiler_directives={"linetrace": True},  # noqa
                    annotate=False,
                ),
                "cmdclass": {"build_ext": build_ext},  # noqa
            }
        )

python

typeerror

cython

0 Answers

Your Answer

Accepted video resources