(no title)
girzel | 3 years ago
>>> from types import SimpleNamespace
>>> d = {"one":1, "two":2}
>>> ns = SimpleNamespace(**d)
>>> ns.two
2
I consider it a bonus that the dict keys are grouped as attributes on an object :)girzel | 3 years ago
>>> from types import SimpleNamespace
>>> d = {"one":1, "two":2}
>>> ns = SimpleNamespace(**d)
>>> ns.two
2
I consider it a bonus that the dict keys are grouped as attributes on an object :)
raymondh|3 years ago
However, I almost never use SimpleNamespace in real code. Dicts offer extra capabilities: get, pop, popitem, clear, copy, keys, values, items). Classes/instances offer extra capabilities: unique and shared keys in distinct namespaces, instances knowing their own type, and an elegant transformation of method calls ``a.m(b, c)`` --> ``type(a).m(a, b, c)``. Dataclasses and named tuples have their advantages as well. In practice, it is almost never that case that SimpleNamespace beats one of the alternatives.