Python3(包括3.6)根本不包括任何对字符串的三向比较支持。虽然富比较运算符__lt__()、__eq__()等的内部实现确实调用了memcmp()(在{}-cf.Objects/bytesobject.c)的C实现中,没有可以利用的内部三方比较函数。在
因此,编写一个通过调用memcmp()提供三方比较函数的C extension是下一个最好的方法:#include
static PyObject* cmp(PyObject* self, PyObject* args) {
PyObject *a = 0, *b = 0;
if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
return 0;
if (!PyBytes_Check(a) || !PyBytes_Check(b)) {
PyErr_SetString(PyExc_TypeError, "only bytes() strings supported");
return 0;
}
Py_ssize_t n = PyBytes_GET_SIZE(a), m = PyBytes_GET_SIZE(b);
char *s = PyBytes_AsString(a), *t = PyBytes_AsString(b);
int r = 0;
if (n == m) {
r = memcmp(s, t, n);
} else if (n < m) {
r = memcmp(s, t, n);
if (!r)
r = -1;
} else {
r = memcmp(s, t, m);
if (!r)
r = 1;
}
return PyLong_FromLong(r);
}
static PyMethodDef bytes_util_methods[] = {
{ "cmp", cmp, METH_VARARGS, "Three way compare 2 bytes() objects." },
{0,0,0,0} };
static struct PyModuleDef bytes_util_def = {
PyModuleDef_HEAD_INIT, "bytes_util", "Three way comparison for strings.",
-1, bytes_util_methods };
PyMODINIT_FUNC PyInit_bytes_util(void) {
Py_Initialize();
return PyModule_Create(&bytes_util_def);
}
编译时使用:
^{pr2}$
测试:>>> import bytes_util
>>> bytes_util.cmp(b'foo', b'barx')
265725
与通过ctypes包调用memcmp不同,这个外部调用与内置字节比较运算符具有相同的开销(因为它们也在标准Python版本中作为C扩展实现)。在