baruch baruch - 6 months ago 23
Python Question

What is the difference between SimpleNamespace and empty class definition?

The following seems to work either way. What is the advantage (other than the nice

repr
) of using
types.SimpleNamespace
? Or is it the same thing?

>>> import types
>>> class Cls():
... pass
...
>>> foo = types.SimpleNamespace() # or foo = Cls()
>>> foo.bar = 42
>>> foo.bar
42
>>> del foo.bar
>>> foo.bar
AttributeError: 'types.SimpleNamespace' object has no attribute 'bar'

Answer

It is explained pretty well in the types module description. It shows you that the 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__