Namespace
Namespace.
A namespace is nothing more than a dictionary with some benefits:
- items use
item.nameas dictionary key. This is checked. - items cannot be overwritten
- items cannot be deleted
- the namespace can be locked for modifications via
lock. - iteration over the namespaces yields the items and not their keys.
Namespace Examples
Examples.
>>> from collections import namedtuple
>>> NamedObject = namedtuple('NamedObject', 'name foo bar')
>>> namespace = Namespace([NamedObject('a', 1, 2)])
>>> namespace.add(NamedObject('b', 3, 4))
>>> namespace['c'] = NamedObject('c', 5, 6)
>>> namespace.is_locked
False
>>> for item in namespace:
... item
NamedObject(name='a', foo=1, bar=2)
NamedObject(name='b', foo=3, bar=4)
NamedObject(name='c', foo=5, bar=6)
>>> for item in namespace.keys():
... item
'a'
'b'
'c'
>>> for item in namespace.values():
... item
NamedObject(name='a', foo=1, bar=2)
NamedObject(name='b', foo=3, bar=4)
NamedObject(name='c', foo=5, bar=6)
>>> namespace['b']
NamedObject(name='b', foo=3, bar=4)
>>> namespace['d']
Traceback (most recent call last):
...
KeyError: 'd'
>>> namespace.get_dym('d')
Traceback (most recent call last):
...
ValueError: 'd'. Known are 'a', 'b' and 'c'.
Locking:
>>> namespace.lock()
>>> namespace.is_locked
True
>>> namespace['d'] = NamedObject('d', 7, 8)
Traceback (most recent call last):
...
ucdp.exceptions.LockError: Namespace is already locked. Cannot add items anymore.
>>> len(namespace)
3
Namespace
Bases: dict
Namespace.
pop
Pop value.
If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.
This operation is forbidden.
popitem
Remove and return a (key, value) pair from the dictionary.
This operation is forbidden.
set_default
Set Default.
If key is in the dictionary, return its value.
If not, insert key with a value of default and return default. default defaults to None.