Python 3.3+typesterm
types.SimpleNamespace
namespaces
A simple container object: attributes are set at creation or later, with dot access. Handy instead of a dict when you want obj.x rather than d['x'].
Syntax
types.SimpleNamespace(**kwargs)
Unlike namedtuple and dataclass, SimpleNamespace has no fixed set of fields: attributes can be added and removed, and it cannot be iterated. Two instances are equal when their attributes are equal — which is also why they are unhashable. vars(ns) returns the underlying dict. A common trick is json.loads(..., object_hook=lambda d: SimpleNamespace(**d)) to read JSON with dot access.
Examples
from types import SimpleNamespace
p = SimpleNamespace(x=1, y=2)
p.z = 3
print(p) # → namespace(x=1, y=2, z=3)
print(p == SimpleNamespace(x=1, y=2, z=3)) # → True
import json
from types import SimpleNamespace
data = json.loads('{"user": {"name": "Ann"}}',
object_hook=lambda d: SimpleNamespace(**d))
print(data.user.name) # → Ann
See also
Open in the full glossarydocs.python.orgReport an inaccuracy