baruch baruch - 1 year ago 69
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

) of using
? Or is it the same thing?

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

Answer Source

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

    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__