top | item 31305261

(no title)

girzel | 3 years ago

I've enjoyed using types.SimpleNamespace:

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

discuss

order

raymondh|3 years ago

As I teacher, types.SimpleNamespace is wonderful for helping people bridge between their understanding of dicts (a fundamental) to classes/instances (a little less fundamental).

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.