36. namespace
— A Namespace class with both attribute and dict style lookup.¶
- class namespace.Namespace[source]¶
A SimpleNamespace subclass that also has dict access methods.
The Namespace class adds three dunder methods to the
types.SimpleNamespace
class: __getitem__, __setitem__ and__delitem__. This allows the attributes also to be accessed with dict methods. Furthermore, it defines an _attrs method to get a list of the defined attributes.Examples
>>> S = Namespace(a=0, b=1) >>> print(S) Namespace(a=0, b=1) >>> S['c'] = 2 >>> S.a = 3 >>> print(S) Namespace(a=3, b=1, c=2) >>> print(S.a, S['a']) 3 3 >>> del S.a >>> T = Namespace(**{'b':1, 'c':2}) >>> print(S, T) Namespace(b=1, c=2) Namespace(b=1, c=2) >>> print(S == T) True >>> del S['c'] >>> print(S == T) False >>> print(T._attrs()) ['b', 'c']