【问题标题】:Cythonize python3 code without using type hints/annotationsCythonize python 代码而不使用类型提示/注释
【发布时间】:2020-08-07 01:24:15
【问题描述】:

是否可以在不使用类型提示/注释的情况下对 python3 代码进行 cythonize?

我正在尝试对一个小型 python3 代码库进行 cythonize,但由于代码中的某些类型提示不正确,这会导致尝试运行 cythonized 代码时出现问题。

这是一个简化的例子,

a.py

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

运行cythonize后尝试运行代码时的错误

TypeError: Expected unicode, got dict

如果我删除 -> str 注释,一切正常。那么,有没有办法告诉 cython 忽略所有注释?

我知道解决此问题的正确方法是修复类型提示,但我正在尝试在修复注释时找到替代解决方案。

这是我的 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"]
)

谢谢。

【问题讨论】:

  • 无论如何,该注释都需要修复。为什么将字符串的字典标记为字符串?

标签: python python-3.x cython cythonize


【解决方案1】:

是的 - 它是in the documentation。只需使用annotation_typing 指令。例如在文件的开头放置:

# cython: annotation_typing = False

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 2015-02-18
    • 2019-09-16
    • 2016-04-03
    • 2017-11-20
    • 2023-03-31
    • 2021-11-27
    • 2021-12-21
    相关资源
    最近更新 更多