sb logoToday I Learned

types.SimpleNamespace in the python standard lib

In the python standard lib, there is a handy object called SimpleNamespace. It is an easy way to namespace other objects and comes with a nice __repr__ built in. I often find myself using it in tests. In situations where I need a generic object, it is more flexible than object because it allows creating and deleting attributes.

import types 

foo = types.SimpleNamespace() = 42
# 42

# AttributeError: 'types.SimpleNamespace' object has no attribute 'bar'

The SimpleNameSpace object is roughly equivalent to the below class:

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__