Skip to content
Merged
Show file tree
Hide file tree
Changes from 8 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
21 changes: 17 additions & 4 deletions Doc/library/types.rst
Original file line number Diff line number Diff line change
Expand Up @@ -479,14 +479,24 @@ Additional Utility Classes and Functions
A simple :class:`object` subclass that provides attribute access to its
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
arguments, those are directly added to the underlying namespace.
Unlike :class:`object`, with :class:`!SimpleNamespace` you can add and remove
attributes.

:py:class:`SimpleNamespace` objects may be initialized either
with keyword arguments or with a single positional argument.
When initialized with keyword arguments,
those are directly added to the underlying namespace.
Alternatively, when initialized with a positional argument,
the underlying namespace will be updated with key-value pairs
from that argument (either a mapping object or
an :term:`iterable` object producing key-value pairs).
All such keys must be strings.

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 +518,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
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,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
23 changes: 21 additions & 2 deletions 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,37 @@ 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})
types.SimpleNamespace(**{1: 2}) # non-string key
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}))
with self.assertRaises(TypeError):
types.SimpleNamespace([[[], 2]]) # non-hashable key

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.
30 changes: 25 additions & 5 deletions Objects/namespaceobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,29 @@ 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;
}
}
if (!PyArg_ValidateKeywordArguments(dict) ||
PyDict_Update(ns->ns_dict, dict) < 0)
{
Py_DECREF(dict);
return -1;
}
Py_DECREF(dict);
}
if (kwds == NULL) {
return 0;
}
Expand Down Expand Up @@ -197,9 +216,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