-
Notifications
You must be signed in to change notification settings - Fork 8
/
compat.pyx
45 lines (39 loc) · 1.06 KB
/
compat.pyx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from cpython.version cimport PY_MAJOR_VERSION
from cpython cimport PyBytes_Check, PyUnicode_Check, PyList_Check, \
PyTuple_Check, PyDict_Check
if PY_MAJOR_VERSION < 3:
string_types = basestring,
else:
string_types = str,
cpdef object s(object x):
if x is None:
return None
elif PY_MAJOR_VERSION < 3:
return x
elif PyBytes_Check(x):
return x.decode('ascii')
elif PyList_Check(x):
return [s(i) for i in x]
elif PyTuple_Check(x):
return tuple([s(i) for i in x])
elif PyDict_Check(x):
return {s(k): s(v) for k, v in x.items()}
else:
return x
cpdef object b(object x):
if x is None:
return None
elif PY_MAJOR_VERSION < 3:
return x
elif PyBytes_Check(x):
return x
elif PyUnicode_Check(x):
return x.encode('ascii')
elif PyList_Check(x):
return [b(i) for i in x]
elif PyTuple_Check(x):
return tuple([b(i) for i in x])
elif PyDict_Check(x):
return {b(k): b(v) for k, v in x.items()}
else:
return x