Skip to content

gh-112068: C API: Add support of nullable arguments in PyArg_Parse (suffix) #121303

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions Lib/test/test_capi/test_getargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1352,6 +1352,59 @@ def test_nested_tuple(self):
"argument 1 must be sequence of length 1, not 0"):
parse(((),), {}, '(' + f + ')', ['a'])

def test_nullable(self):
parse = _testcapi.parse_tuple_and_keywords

def check(format, arg, allows_none=False):
# Because some format units (such as y*) require cleanup,
# we force the parsing code to perform the cleanup by adding
# an argument that always fails.
# By checking for an exception, we ensure that the parsing
# of the first argument was successful.
self.assertRaises(OverflowError, parse,
(arg, 256), {}, format + '?b', ['a', 'b'])
self.assertRaises(OverflowError, parse,
(None, 256), {}, format + '?b', ['a', 'b'])
self.assertRaises(OverflowError, parse,
(arg, 256), {}, format + 'b', ['a', 'b'])
self.assertRaises(OverflowError if allows_none else TypeError, parse,
(None, 256), {}, format + 'b', ['a', 'b'])

check('b', 42)
check('B', 42)
check('h', 42)
check('H', 42)
check('i', 42)
check('I', 42)
check('n', 42)
check('l', 42)
check('k', 42)
check('L', 42)
check('K', 42)
check('f', 2.5)
check('d', 2.5)
check('D', 2.5j)
check('c', b'a')
check('C', 'a')
check('p', True, allows_none=True)
check('y', b'buffer')
check('y*', b'buffer')
check('y#', b'buffer')
check('s', 'string')
check('s*', 'string')
check('s#', 'string')
check('z', 'string', allows_none=True)
check('z*', 'string', allows_none=True)
check('z#', 'string', allows_none=True)
check('w*', bytearray(b'buffer'))
check('U', 'string')
check('S', b'bytes')
check('Y', bytearray(b'bytearray'))
check('O', object, allows_none=True)

# TODO: Not tested: es?, es#?, et?, et#?, O!, O&
# TODO: Not implemented: (...)?

@unittest.skipIf(_testinternalcapi is None, 'needs _testinternalcapi')
def test_gh_119213(self):
rc, out, err = script_helper.assert_python_ok("-c", """if True:
Expand Down
11 changes: 3 additions & 8 deletions Modules/_ctypes/_ctypes.c
Original file line number Diff line number Diff line change
Expand Up @@ -3620,8 +3620,7 @@ _validate_paramflags(ctypes_state *st, PyTypeObject *type, PyObject *paramflags)
PyObject *name = Py_None;
PyObject *defval;
PyObject *typ;
if (!PyArg_ParseTuple(item, "i|OO", &flag, &name, &defval) ||
!(name == Py_None || PyUnicode_Check(name)))
if (!PyArg_ParseTuple(item, "i|U?O", &flag, &name, &defval))
{
PyErr_SetString(PyExc_TypeError,
"paramflags must be a sequence of (int [,string [,value]]) tuples");
Expand Down Expand Up @@ -3686,10 +3685,8 @@ PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
void *handle;
PyObject *paramflags = NULL;

if (!PyArg_ParseTuple(args, "O|O", &ftuple, &paramflags))
if (!PyArg_ParseTuple(args, "O|O?", &ftuple, &paramflags))
return NULL;
if (paramflags == Py_None)
paramflags = NULL;

ftuple = PySequence_Tuple(ftuple);
if (!ftuple)
Expand Down Expand Up @@ -3804,10 +3801,8 @@ PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
GUID *iid = NULL;
Py_ssize_t iid_len = 0;

if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
if (!PyArg_ParseTuple(args, "is|O?z#", &index, &name, &paramflags, &iid, &iid_len))
return NULL;
if (paramflags == Py_None)
paramflags = NULL;

ctypes_state *st = get_module_state_by_def(Py_TYPE(type));
if (!_validate_paramflags(st, type, paramflags)) {
Expand Down
13 changes: 3 additions & 10 deletions Modules/_json.c
Original file line number Diff line number Diff line change
Expand Up @@ -1208,23 +1208,16 @@ encoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static char *kwlist[] = {"markers", "default", "encoder", "indent", "key_separator", "item_separator", "sort_keys", "skipkeys", "allow_nan", NULL};

PyEncoderObject *s;
PyObject *markers, *defaultfn, *encoder, *indent, *key_separator;
PyObject *markers = Py_None, *defaultfn, *encoder, *indent, *key_separator;
PyObject *item_separator;
int sort_keys, skipkeys, allow_nan;

if (!PyArg_ParseTupleAndKeywords(args, kwds, "OOOOUUppp:make_encoder", kwlist,
&markers, &defaultfn, &encoder, &indent,
if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!?OOOUUppp:make_encoder", kwlist,
&PyDict_Type, &markers, &defaultfn, &encoder, &indent,
&key_separator, &item_separator,
&sort_keys, &skipkeys, &allow_nan))
return NULL;

if (markers != Py_None && !PyDict_Check(markers)) {
PyErr_Format(PyExc_TypeError,
"make_encoder() argument 1 must be dict or None, "
"not %.200s", Py_TYPE(markers)->tp_name);
return NULL;
}

s = (PyEncoderObject *)type->tp_alloc(type, 0);
if (s == NULL)
return NULL;
Expand Down
14 changes: 3 additions & 11 deletions Modules/_threadmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -1878,10 +1878,10 @@ thread_PyThread_start_joinable_thread(PyObject *module, PyObject *fargs,
PyObject *func = NULL;
int daemon = 1;
thread_module_state *state = get_thread_state(module);
PyObject *hobj = NULL;
PyObject *hobj = Py_None;
if (!PyArg_ParseTupleAndKeywords(fargs, fkwargs,
"O|Op:start_joinable_thread", keywords,
&func, &hobj, &daemon)) {
"O|O!?p:start_joinable_thread", keywords,
&func, state->thread_handle_type, &hobj, &daemon)) {
return NULL;
}

Expand All @@ -1891,14 +1891,6 @@ thread_PyThread_start_joinable_thread(PyObject *module, PyObject *fargs,
return NULL;
}

if (hobj == NULL) {
hobj = Py_None;
}
else if (hobj != Py_None && !Py_IS_TYPE(hobj, state->thread_handle_type)) {
PyErr_SetString(PyExc_TypeError, "'handle' must be a _ThreadHandle");
return NULL;
}

if (PySys_Audit("_thread.start_joinable_thread", "OiO", func, daemon,
hobj) < 0) {
return NULL;
Expand Down
3 changes: 1 addition & 2 deletions Modules/mmapmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
#endif

#include <Python.h>
#include "pycore_abstract.h" // _Py_convert_optional_to_ssize_t()
#include "pycore_bytesobject.h" // _PyBytes_Find()
#include "pycore_fileutils.h" // _Py_stat_struct

Expand Down Expand Up @@ -512,7 +511,7 @@ mmap_read_method(mmap_object *self,
Py_ssize_t num_bytes = PY_SSIZE_T_MAX, remaining;

CHECK_VALID(NULL);
if (!PyArg_ParseTuple(args, "|O&:read", _Py_convert_optional_to_ssize_t, &num_bytes))
if (!PyArg_ParseTuple(args, "|n?:read", &num_bytes))
return NULL;
CHECK_VALID(NULL);

Expand Down
Loading
Loading