Python: The SimpleNamespace Utility Class

less than 1 minute read

The SimpleNamespace type from the types library provides an alternative to an empty class (class MyClass: pass) from which one can add and remove attributes.

import types

enki = types.SimpleNamespace()

enki.type = 'God'
print(enki.type) # God

del enki.type
# object has no attribute 'type'


A simple object subclass that provides attribute access to its namespace, as well as a meaningful repr.

Unlike object, with SimpleNamespace you can add and remove attributes. If a SimpleNamespace object is initialized with keyword arguments, those are directly added to the underlying namespace.

SimpleNamespace may be useful as a replacement for class NS: pass. However, for a structured record type use namedtuple() instead.