Cython 扩展与 Python2 不兼容。

Cython extension not compatible with Python2.

我正在使用 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] = '[=12=]'
    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 str == Python 3 bytes

Python 2 unicode == Python 3 str.

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

在 Python 2 上,str.decode return 是一个 unicode 对象。您收到一个错误,因为它与函数签名中的 str 对象不匹配。在 Python 3 bytes.decode return 上有一个 str 对象(相当于一个 Python 2 unicode 对象)。这与函数签名中的 str 匹配,所以没问题。

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

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