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:
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
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.
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.