Python 2.7 Cython扩展与Python2不兼容。
我使用的是Python 2.7 Cython扩展与Python2不兼容。,python-2.7,cython,cythonize,Python 2.7,Cython,Cythonize,我使用的是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)
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
我在Python3上没有看到这个错误。我想在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)
cpdef str编码(双纬度,双经度,整数精度=12):
"""
对以浮点参数表示的位置(纬度、经度)进行编码
具有字符计数精度的geohash。
"""
cdef(双,双)横向间隔
cdef(双,双)长间隔
横向间隔,纵向间隔=(-90.0,90.0),(-180.0,180.0)
cdef char*result=malloc((精度+1)*sizeof(char))
如果没有结果:
提高内存错误()
结果[精度]='\0'
cdef int位=0
cdef int ch=0
偶数=真
cdef int i=0
尝试:
而我认为:
即使:
mid=(lon_区间[0]+lon_区间[1])/2
如果经度>中间:
ch |=位[位]
lon_间隔=(中间,lon_间隔[1])
其他:
lon_区间=(lon_区间[0],中间)
其他:
mid=(横向间隔[0]+横向间隔[1])/2
如果纬度>中部:
ch |=位[位]
横向间隔=(中间,横向间隔[1])
其他:
横向间隔=(横向间隔[0],中间)
偶数
如果位<4:
位+=1
其他:
结果[i]=uu base32[ch]
i+=1
位=0
ch=0
返回结果[:i]。解码('ascii')
最后:
免费(结果)
python2str
==python3bytes
Python 2unicode
==Python 3str
Cython在Python2上将Cchar[]
转换为str
,在Python3上转换为bytes
(因为这是两种情况下最符合逻辑的转换)
在Python2上,str.decode
返回一个unicode
对象。您会收到一个错误,因为它与函数签名中的str
对象不匹配。在Python3上,decode返回一个str
对象(相当于Python2unicode
对象)。这与函数签名中的str
匹配,因此可以
最简单的解决方案是停止在函数签名中指定返回类型——指定Python对象的确切类型几乎没有什么好处:
cpdef encode(double latitude, double longitude, int precision=12):