【问题标题】:Cython extension not compatible with Python2.Cython 扩展与 Python2 不兼容。
【发布时间】:2018-12-16 06:28:38
【问题描述】:

我正在使用Cython 扩展代码,但此代码抛出错误:

/Users/rkumar/src/fast-geohash/cython/_fast_geohash.pyx in _fast_geohash.encode()
     56                 ch = 0
     57
---> 58         return result[:i].decode('ascii')
     59     finally:
     60         free(result)

TypeError: Expected str, got unicode

我在 Python 3 上没有收到这个错误。我想在 Python2 上使用这个扩展。我不知道如何解决这个问题。 这是扩展代码:

cpdef str encode(double latitude, double longitude, int precision=12):
    """
    Encode a position given in float arguments latitude, longitude to
    a geohash which will have the character count precision.
    """
    cdef (double, double) lat_interval
    cdef (double, double) lon_interval
    lat_interval, lon_interval = (-90.0, 90.0), (-180.0, 180.0)
    cdef char* result = <char *> malloc((precision + 1) * sizeof(char))
    if not result:
        raise MemoryError()
    result[precision] = '\0'
    cdef int bit = 0
    cdef int ch = 0
    even = True
    cdef int i = 0
    try:
        while i < precision:
            if even:
                mid = (lon_interval[0] + lon_interval[1]) / 2
                if longitude > mid:
                    ch |= bits[bit]
                    lon_interval = (mid, lon_interval[1])
                else:
                    lon_interval = (lon_interval[0], mid)
            else:
                mid = (lat_interval[0] + lat_interval[1]) / 2
                if latitude > mid:
                    ch |= bits[bit]
                    lat_interval = (mid, lat_interval[1])
                else:
                    lat_interval = (lat_interval[0], mid)
            even = not even
            if bit < 4:
                bit += 1
            else:
                result[i] = __base32[ch]
                i += 1
                bit = 0
                ch = 0

        return result[:i].decode('ascii')
    finally:
        free(result)

【问题讨论】:

    标签: python-2.7 cython cythonize


    【解决方案1】:

    Python 2 str == Python 3 bytes

    Python 2 unicode == Python 3 str

    Cython 将您的 C char[] 转换为 Python 2 上的 str 和 Python 3 上的 bytes(因为这是两种情况下最合乎逻辑的转换)。

    在 Python 2 上,str.decode 返回一个 unicode 对象。您会收到一个错误,因为它与函数签名中的 str 对象不匹配。在 Python 3 上,bytes.decode 返回一个 str 对象(相当于 Python 2 的 unicode 对象)。这与函数签名中的str 匹配,所以很好。

    最简单的解决方案是停止在函数签名中指定返回类型 - 指定 Python 对象的确切类型几乎没有什么好处:

    cpdef encode(double latitude, double longitude, int precision=12):
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 1970-01-01
      • 2016-12-19
      • 2021-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多