sb logoToday I Learned

1 post by zacharyschumacher

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()
foo.bar = 42
print(foo.bar)
# 42

del foo.bar
print(foo.bar)
# AttributeError: 'types.SimpleNamespace' object has no attribute 'bar'

The SimpleNameSpace object is roughly equivalent to the below class:

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__