gh-108191: Add support of positional argument in SimpleNamespace constructor (GH-108195)

SimpleNamespace({'a': 1, 'b': 2}) and SimpleNamespace([('a', 1), ('b', 2)])
are now the same as SimpleNamespace(a=1, b=2).
This commit is contained in:
Serhiy Storchaka 2024-04-25 00:39:54 +03:00 committed by GitHub
parent 85ec1c2dc6
commit 93b7ed7c6b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
5 changed files with 92 additions and 20 deletions

View file

@ -43,10 +43,28 @@ namespace_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
namespace_init(_PyNamespaceObject *ns, PyObject *args, PyObject *kwds)
{
if (PyTuple_GET_SIZE(args) != 0) {
PyErr_Format(PyExc_TypeError, "no positional arguments expected");
PyObject *arg = NULL;
if (!PyArg_UnpackTuple(args, _PyType_Name(Py_TYPE(ns)), 0, 1, &arg)) {
return -1;
}
if (arg != NULL) {
PyObject *dict;
if (PyDict_CheckExact(arg)) {
dict = Py_NewRef(arg);
}
else {
dict = PyObject_CallOneArg((PyObject *)&PyDict_Type, arg);
if (dict == NULL) {
return -1;
}
}
int err = (!PyArg_ValidateKeywordArguments(dict) ||
PyDict_Update(ns->ns_dict, dict) < 0);
Py_DECREF(dict);
if (err) {
return -1;
}
}
if (kwds == NULL) {
return 0;
}
@ -227,7 +245,7 @@ static PyMethodDef namespace_methods[] = {
PyDoc_STRVAR(namespace_doc,
"SimpleNamespace(**kwargs)\n\
"SimpleNamespace(mapping_or_iterable=(), /, **kwargs)\n\
--\n\n\
A simple attribute-based namespace.");