Reputation: 5104
Simple question: How do I merge Python's SimpleNamespace?
It looks like there is no way to do this in a simple command like a.update(b)
or a | b
. In fact, I haven't even found a way to systematically access all attributes of a SimpleNamespace.
Any leads?
Upvotes: 4
Views: 1495
Reputation: 51989
Each SimpleNamespace
has a __dict__
slot, which gives access to its actual attributes. **
-unpacking the __dict__
from multiple SimpleNamespace
s into a new SimpleNamespace
effectively merges them.
>>> from types import SimpleNamespace
>>> first = SimpleNamespace(a=0, b=1, c=2)
>>> second = SimpleNamespace(x=0, y=1, z=2)
>>> SimpleNamespace(**first.__dict__, **second.__dict__)
namespace(a=0, b=1, c=2, x=0, y=1, z=2)
Note that it is a TypeError
to merge namespaces with overlapping attributes this way.
To merge namespaces with possibly overlapping keys, use an intermediate dictionary and unpack it again (**{...}
). The values of later namespaces take precedence with this scheme.
>>> first = SimpleNamespace(a=0, b=1, c=2)
>>> second = SimpleNamespace(c=0, d=1, e=2)
>>> SimpleNamespace(**{**first.__dict__, **second.__dict__})
namespace(a=0, b=1, c=0, d=1, e=2)
Upvotes: 8