8000 gh-108191: Add support of positional argument in SimpleNamespace constructor by serhiy-storchaka · Pull Request #108195 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-108191: Add support of positional argument in SimpleNamespace constructor #108195

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 17 commits into from
Apr 24, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
14 changes: 12 additions & 2 deletions Doc/library/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -480,13 +480,20 @@ Additional Utility Classes and Functions
namespace, as well as a meaningful repr.

Unlike :class:`object`, with ``SimpleNamespace`` you can add and remove
attributes. If a ``SimpleNamespace`` object is initialized with keyword
attributes.
The :class:`!SimpleNamespace` constructor can take a positional argument
which must be a mapping object with string keys or an :term:`iterable`
object producing key-value pairs with string keys.
Key-value pairs from the mapping object or the iterable object are
directly added to the underlying namespace.
If a ``SimpleNamespace`` object is initialized with keyword
arguments, those are directly added to the underlying namespace.

The type is roughly equivalent to the following code::

class SimpleNamespace:
def __init__(self, /, **kwargs):
def __init__(self, mapping_or_iterable=(), /, **kwargs):
self.__dict__.update(mapping_or_iterable)
self.__dict__.update(kwargs)

def __repr__(self):
Expand All @@ -508,6 +515,9 @@ Additional Utility Classes and Functions
Attribute order in the repr changed from alphabetical to insertion (like
``dict``).

.. versionchanged:: 3.13
Added support of an optional positional argument.

.. function:: DynamicClassAttribute(fget=None, fset=None, fdel=None, doc=None)

Route attribute access on a class to __getattr__.
Expand Down
8 changes: 8 additions & 0 deletions Doc/whatsnew/3.13.rst
< 8000 /form>
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,14 @@ traceback
to format the nested exceptions of a :exc:`BaseExceptionGroup` instance, recursively.
(Contributed by Irit Katriel in :gh:`105292`.)

types
-----

* :class:`~types.SimpleNamespace` constructor allows now to specify initial
values of attributes as a positional argument which must be a mapping or
an iterable or key-value pairs.
(Contributed by Serhiy Storchaka in :gh:`108191`.)

typing
------

Expand Down
19 changes: 18 additions & 1 deletion Lib/test/test_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from test.support import run_with_locale, cpython_only
import collections.abc
from collections import namedtuple
from collections import namedtuple, UserDict
import copy
import gc
import inspect
Expand Down Expand Up @@ -1732,18 +1732,35 @@ def test_constructor(self):
ns1 = types.SimpleNamespace()
ns2 = types.SimpleNamespace(x=1, y=2)
ns3 = types.SimpleNamespace(**dict(x=1, y=2))
ns4 = types.SimpleNamespace({'x': 1, 'y': 2}, x=4, z=3)
ns5 = types.SimpleNamespace([['x', 1], ['y', 2]], x=4, z=3)
ns6 = types.SimpleNamespace(UserDict({'x': 1, 'y': 2}), x=4, z=3)

with self.assertRaises(TypeError):
types.SimpleNamespace([], [])
with self.assertRaises(TypeError):
types.SimpleNamespace(1, 2, 3)
with self.assertRaises(TypeError):
types.SimpleNamespace(**{1: 2})
with self.assertRaises(TypeError):
types.SimpleNamespace({1: 2})
with self.assertRaises(TypeError):
types.SimpleNamespace([[1, 2]])
with self.assertRaises(TypeError):
types.SimpleNamespace(UserDict({1: 2}))

self.assertEqual(len(ns1.__dict__), 0)
self.assertEqual(vars(ns1), {})
self.assertEqual(len(ns2.__dict__), 2)
self.assertEqual(vars(ns2), {'y': 2, 'x': 1})
self.assertEqual(len(ns3.__dict__), 2)
self.assertEqual(vars(ns3), {'y': 2, 'x': 1})
self.assertEqual(len(ns4.__dict__), 3)
self.assertEqual(vars(ns4), {'x': 4, 'y': 2, 'z': 3})
self.assertEqual(len(ns5.__dict__), 3)
self.assertEqual(vars(ns5), {'x': 4, 'y': 2, 'z': 3})
self.assertEqual(len(ns6.__dict__), 3)
self.assertEqual(vars(ns6), {'x': 4, 'y': 2, 'z': 3})

def test_unbound(self):
ns1 = vars(types.SimpleNamespace())
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
The :class:`types.SimpleNamespace` now accepts an optional positional
argument which specifies initial values of attributes as a dict or an
iterable of key-value pairs.
44 changes: 39 additions & 5 deletions Objects/namespaceobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include "Python.h"
#include "pycore_namespace.h" // _PyNamespace_Type
#include "pycore_runtime.h" // _Py_ID

#include <stddef.h> // offsetof()

Expand Down Expand Up @@ -43,10 +44,42 @@ 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;
int ret = 0;
if (PyDict_CheckExact(arg)) {
dict = Py_NewRef(arg);
}
else {
dict = PyDict_New();
if (dict == NULL) {
return -1;
}
PyObject *func;
ret = PyObject_GetOptionalAttr(arg, &_Py_ID(keys), &func);
if (ret > 0) {
Py_DECREF(func);
ret = PyDict_Merge(dict, arg, 1);
}
else if (ret == 0) {
ret = PyDict_MergeFromSeq2(dict, arg, 1);
}
}
if (ret < 0 ||
!PyArg_ValidateKeywordArguments(dict) ||
PyDict_Update(ns->ns_dict, dict) < 0)
{
ret = -1;
}
Py_DECREF(dict);
if (ret < 0) {
return -1;
}
}
if (kwds == NULL) {
return 0;
}
Expand Down Expand Up @@ -197,9 +230,10 @@ static PyMethodDef namespace_methods[] = {


PyDoc_STRVAR(namespace_doc,
"A simple attribute-based namespace.\n\
\n\
SimpleNamespace(**kwargs)");
"SimpleNamespace(mapping_or_iterable=(), /, **kwargs)\n"
"--\n"
"\n"
"A simple attribute-based namespace.");

PyTypeObject _PyNamespace_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
Expand Down
0