简体   繁体   中英

Cythonize python3 code without using type hints/annotations

Is it possible to cythonize python3 code without using type hints/annotations?

I am trying to cythonize a small python3 code base and I am facing some issues as some of the type hints in the code are incorrect and this is causing issues when trying to run the cythonized code.

Here is a simplified example,

a.py

def test_func(arg1) -> str:
    return {"hello": "world"}

The error when trying to run the code after running cythonize

TypeError: Expected unicode, got dict

Everything works fine if I remove the -> str annotation. So, it there a way to tell cython to ignore all annotations?

I am aware the correct way of resolving this is to fix the type hints, but I am trying to find an alternate solution while I fix the annotations.

This is my setup.py

#cython: language_level=3
#cython: annotation_typing=False
from setuptools import setup
from setuptools.extension import Extension

from Cython.Build import cythonize
from Cython.Distutils import build_ext

setup(
    name="lib",
    ext_modules=cythonize(
        [
           Extension("pkg1.*", ["pkg1/*.py"], include_dirs = ["."], extra_compile_args = ['-O3']),
        ],
        build_dir="build",
        compiler_directives=dict(
        always_allow_keywords=True,
        language_level=3)),
    cmdclass=dict(
        build_ext=build_ext
    ),
    packages=["pkg1"]
)

Thanks.

Yes - it's in the documentation . Just use the annotation_typing directive. For example at the start of a file put:

# cython: annotation_typing = False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM