Namespace¶
Accretive namespaces are similar to types.SimpleNamespace
, but with
the added property that once an attribute is set, it cannot be altered or
removed. This makes them useful for configurations and settings that should
remain immutable once defined.
>>> from accretive import Namespace
Let us illustrate this use case by defining a configuration namespace for a web application.
Initialization¶
Accretive namespaces can be initialized from zero or more dictionaries or iterables over key-value pairs and zero or more keyword arguments.
>>> config = Namespace(
... ( ( 'host', 'localhost' ), ( 'port', 8080 ) ),
... { 'debug': True, 'database': 'sqlite:///app.db' },
... api_key = '12345-ABCDE' )
>>> config
accretive.namespaces.Namespace( host = 'localhost', port = 8080, debug = True, database = 'sqlite:///app.db', api_key = '12345-ABCDE' )
Immutability¶
Existing attributes cannot be reassigned.
>>> config.host = '127.0.0.1'
Traceback (most recent call last):
...
accretive.exceptions.IndelibleAttributeError: Cannot reassign or delete existing attribute 'host'.
Or deleted.
>>> del config.port
Traceback (most recent call last):
...
accretive.exceptions.IndelibleAttributeError: Cannot reassign or delete existing attribute 'port'.
Attribute Assignment¶
However, new attributes can be assigned.
>>> config.new_feature = 'enabled'
>>> config
accretive.namespaces.Namespace( host = 'localhost', port = 8080, debug = True, database = 'sqlite:///app.db', api_key = '12345-ABCDE', new_feature = 'enabled' )
Copies¶
To copy an accretive namespace, access its underlying __dict__ and feed that
as keyword arguments to a new namespace. This is the same way as how it would
be done with types.SimpleNamespace
.
>>> from types import SimpleNamespace
>>> config_copy = Namespace( **config.__dict__ ) #**
>>> config_copy
accretive.namespaces.Namespace( host = 'localhost', port = 8080, debug = True, database = 'sqlite:///app.db', api_key = '12345-ABCDE', new_feature = 'enabled' )
>>> ns = SimpleNamespace( **config.__dict__ ) #**
Comparison¶
The copies are equivalent to their originals.
>>> config == config_copy
True
>>> config_copy == ns
True
Modifying a copy causes it to become non-equivalent, as expected.
>>> config_copy.another_feature = 'disabled'
>>> config == config_copy
False
>>> config_copy != ns
True