gh-132987: Support __index__() in the posix module (GH-133096)

Support it for the dev_t values in mknod(), major(), minor() and makedev(),
CPU numbers in sched_setaffinity(), group numbers in setgroups(),
configuration name in fpathconf(), pathconf(), confstr(), and sysconf().
This commit is contained in:
Serhiy Storchaka 2025-04-29 16:14:47 +03:00 committed by GitHub
parent bba14c3e01
commit 07edc0d2b2
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1035,21 +1035,34 @@ _PyLong_FromDev(dev_t dev)
static int static int
_Py_Dev_Converter(PyObject *obj, void *p) _Py_Dev_Converter(PyObject *obj, void *p)
{ {
if (!PyLong_Check(obj)) {
obj = _PyNumber_Index(obj);
if (obj == NULL) {
return 0;
}
}
else {
Py_INCREF(obj);
}
assert(PyLong_Check(obj));
#ifdef NODEV #ifdef NODEV
if (PyLong_Check(obj) && _PyLong_IsNegative((PyLongObject *)obj)) { if (_PyLong_IsNegative((PyLongObject *)obj)) {
int overflow; int overflow;
long long result = PyLong_AsLongLongAndOverflow(obj, &overflow); long long result = PyLong_AsLongLongAndOverflow(obj, &overflow);
if (result == -1 && PyErr_Occurred()) { if (result == -1 && PyErr_Occurred()) {
Py_DECREF(obj);
return 0; return 0;
} }
if (!overflow && result == (long long)NODEV) { if (!overflow && result == (long long)NODEV) {
*((dev_t *)p) = NODEV; *((dev_t *)p) = NODEV;
Py_DECREF(obj);
return 1; return 1;
} }
} }
#endif #endif
unsigned long long result = PyLong_AsUnsignedLongLong(obj); unsigned long long result = PyLong_AsUnsignedLongLong(obj);
Py_DECREF(obj);
if (result == (unsigned long long)-1 && PyErr_Occurred()) { if (result == (unsigned long long)-1 && PyErr_Occurred()) {
return 0; return 0;
} }
@ -8499,7 +8512,7 @@ os_sched_setaffinity_impl(PyObject *module, pid_t pid, PyObject *mask)
while ((item = PyIter_Next(iterator))) { while ((item = PyIter_Next(iterator))) {
long cpu; long cpu;
if (!PyLong_Check(item)) { if (!PyIndex_Check(item)) {
PyErr_Format(PyExc_TypeError, PyErr_Format(PyExc_TypeError,
"expected an iterator of ints, " "expected an iterator of ints, "
"but iterator yielded %R", "but iterator yielded %R",
@ -9874,7 +9887,7 @@ os_setgroups(PyObject *module, PyObject *groups)
PyMem_Free(grouplist); PyMem_Free(grouplist);
return NULL; return NULL;
} }
if (!PyLong_Check(elem)) { if (!PyIndex_Check(elem)) {
PyErr_SetString(PyExc_TypeError, PyErr_SetString(PyExc_TypeError,
"groups must be integers"); "groups must be integers");
Py_DECREF(elem); Py_DECREF(elem);
@ -13643,7 +13656,7 @@ conv_confname(PyObject *module, PyObject *arg, int *valuep, const char *tablenam
} }
int success = 0; int success = 0;
if (!PyLong_Check(arg)) { if (!PyIndex_Check(arg)) {
PyErr_SetString(PyExc_TypeError, PyErr_SetString(PyExc_TypeError,
"configuration names must be strings or integers"); "configuration names must be strings or integers");
} else { } else {