Description
Feature or enhancement
Proposal:
types.SimpleNamespace is a lightweight object for grouping attributes. However, it lacks a built-in way to update multiple attributes at once using keyword arguments.
Currently, users must write:
ns.__dict__.update({'x': 1, 'y': 2})
This leaks implementation details and reduces code clarity. A built-in method would make this cleaner and more idiomatic.
Add an update(**kwargs) method to SimpleNamespace that updates the namespace in place:
from types import SimpleNamespace
ns = SimpleNamespace(a=1)
ns.update(b=2, c=3)
print(ns) # namespace(a=1, b=2, c=3)
-
Implemented in Objects/namespaceobject.c
-
Calls PyDict_Update(self->dict, kwargs) directly
-
Uses the --\n\n signature string convention so inspect.signature() works
-
Added test in Lib/test/test_types.py
Benchmarks:
Measured over 1 million repetitions:
SimpleNamespace.update() | 1.25 s
dict.update() | 1.10 s
class().attr = value | 0.55 s
Testing:
Unit test confirms that update() modifies or adds attributes correctly
inspect.signature(SimpleNamespace.update) returns a valid signature
Full CPython test suite run — no regressions introduced
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
https://discuss.python.org/t/update-method-for-simplenamespace/97207