This is explained pretty well in the types module description. It shows you that types.SimpleNamespace is roughly equivalent to this:
class SimpleNamespace:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def __repr__(self):
keys = sorted(self.__dict__)
items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys)
return "{}({})".format(type(self).__name__, ", ".join(items))
def __eq__(self, other):
return self.__dict__ == other.__dict__
This provides the following advantages over an empty class:
- It allows you to initialize attributes while constructing the object:
sn = SimpleNamespace(a=1, b=2) - It provides a readable
repr():eval(repr(sn)) == sn - It overrides the default comparison. Instead of comparing by
id(), it compares attribute values instead.