Update() method for SimpleNamespace

I am a uni student who wants to contribute for a project and I had the Idea of implementing a update() method to SimpleNamespace as a form of increasing clarity and readability.

Currently, there is no built-in way to update multiple attributes at once. Users must do:

ns.__dict__.update({'a': 1, 'b': 2})

This accesses internal implementation details and is not ideal for readability or clarity.
Introduce an update(**kwargs) method to SimpleNamespace:

from types import SimpleNamespace

ns = SimpleNamespace(x=10)
ns.update(y=20, z=30)
print(ns)  # namespace(x=10, y=20, z=30)
1 Like

Not a bad idea, I think.

If you get on it, see if you could optimize it

User defined class is ~6x faster for both __getitem__ and __setitem__.

Thanks! I’m glad to hear the idea seems reasonable.

I’ll definitely take performance into account. I’ll benchmark SimpleNamespace against a user-defined class and ensure the update() method is implemented efficiently — likely by calling PyDict_Update() directly on __dict__ to avoid unnecessary overhead.

I’ve now implemented the update(**kwargs) method, and made sure it’s efficient. Specifically, it calls PyDict_Update() directly on the instance’s __dict__, rather than looping over attributes or using setattr in Python.

So while SimpleNamespace itself may be slower than plain classes for per-attribute __setattr__ or __getitem__, this method:

  • Adds no extra attribute overhead
  • Uses the same optimized internal path as dict.update()
  • Keeps the operation one-shot and native

SimpleNamespace.update: 1.2503997999992862
dict.update: 1.1033925020019524
class attribute set: 0.5542851019999944

What’s the use-case? Adding complexity to the interface just to save a few lines usually isn’t a good trade-off. Have you explored copy.replace()?

A

4 Likes

Another option, which would be a bit more generic is to implement operator.set_many_attrs / operator.set_many_items.

1 Like

You don’t need to access “internal implementation details” if you call the built-in function vars instead, and also note that the dict.update method accepts variable keyword arguments:

vars(ns).update(a=1, b=2)

FWIW I consider __dict__ a well-documented language feature rather than an implementation detail.

5 Likes

This would prevent using “update” as an ordinary attribute in a namespace. Or rather, it would be very confusing to have an existing method that could clash wit an attribut of the same name. Right now there is no attribute except dunders, and I bet that it’s by design to avoid these clashes.

8 Likes

Yes, it is by design.

Note also the name – SimpleNamespace. If you need something more complex, create other class.

2 Likes