+class SubHandler(Handler):
+ r"""SubHandler(parent) -> SubHandler instance :: Handles subcommands.
+
+ This is a helper class to build sub handlers that needs to reference the
+ parent handler.
+
+ parent - Parent Handler object.
+ """
+
+ def __init__(self, parent):
+ r"Initialize the object, see the class documentation for details."
+ self.parent = parent
+
+class ContainerSubHandler(SubHandler):
+ r"""ContainerSubHandler(parent) -> ContainerSubHandler instance.
+
+ This is a helper class to implement ListSubHandler and DictSubHandler. You
+ should not use it directly.
+
+ The container attribute to handle and the class of objects that it
+ contains can be defined by calling the constructor or in a more declarative
+ way as class attributes, like:
+
+ class TestHandler(ContainerSubHandler):
+ _cont_subhandler_attr = 'some_cont'
+ _cont_subhandler_class = SomeClass
+
+ This way, the parent's some_cont attribute (self.parent.some_cont)
+ will be managed automatically, providing the commands: add, update,
+ delete, get and show. New items will be instances of SomeClass,
+ which should provide a cmp operator to see if the item is on the
+ container and an update() method, if it should be possible to modify
+ it. If SomeClass has an _add, _update or _delete attribute, it set
+ them to true when the item is added, updated or deleted respectively
+ (in case that it's deleted, it's not removed from the container,
+ but it's not listed either).
+ """
+
+ def __init__(self, parent, attr=None, cls=None):
+ r"Initialize the object, see the class documentation for details."
+ self.parent = parent
+ if attr is not None:
+ self._cont_subhandler_attr = attr
+ if cls is not None:
+ self._cont_subhandler_class = cls
+
+ def _attr(self, attr=None):
+ if attr is None:
+ return getattr(self.parent, self._cont_subhandler_attr)
+ setattr(self.parent, self._cont_subhandler_attr, attr)
+
+ def _vattr(self):
+ if isinstance(self._attr(), dict):
+ return dict([(k, i) for (k, i) in self._attr().items()
+ if not hasattr(i, '_delete') or not i._delete])
+ return [i for i in self._attr()
+ if not hasattr(i, '_delete') or not i._delete]
+
+ @handler(u'Add a new item')
+ def add(self, *args, **kwargs):
+ r"add(...) -> None :: Add an item to the list."
+ item = self._cont_subhandler_class(*args, **kwargs)
+ if hasattr(item, '_add'):
+ item._add = True
+ key = item
+ if isinstance(self._attr(), dict):
+ key = item.as_tuple()[0]
+ # do we have the same item? then raise an error
+ if key in self._vattr():
+ raise ItemAlreadyExistsError(item)
+ # do we have the same item, but logically deleted? then update flags
+ if key in self._attr():
+ index = key
+ if not isinstance(self._attr(), dict):
+ index = self._attr().index(item)
+ if hasattr(item, '_add'):
+ self._attr()[index]._add = False
+ if hasattr(item, '_delete'):
+ self._attr()[index]._delete = False
+ else: # it's *really* new
+ if isinstance(self._attr(), dict):
+ self._attr()[key] = item
+ else:
+ self._attr().append(item)
+
+ @handler(u'Update an item')
+ def update(self, index, *args, **kwargs):
+ r"update(index, ...) -> None :: Update an item of the container."
+ # TODO make it right with metaclasses, so the method is not created
+ # unless the update() method really exists.
+ # TODO check if the modified item is the same of an existing one
+ if not isinstance(self._attr(), dict):
+ index = int(index) # TODO validation
+ if not hasattr(self._cont_subhandler_class, 'update'):
+ raise CommandNotFoundError(('update',))
+ try:
+ item = self._vattr()[index]
+ item.update(*args, **kwargs)
+ if hasattr(item, '_update'):
+ item._update = True
+ except IndexError:
+ raise ItemNotFoundError(index)
+
+ @handler(u'Delete an item')
+ def delete(self, index):
+ r"delete(index) -> None :: Delete an item of the container."
+ if not isinstance(self._attr(), dict):
+ index = int(index) # TODO validation
+ try:
+ item = self._vattr()[index]
+ if hasattr(item, '_delete'):
+ item._delete = True
+ else:
+ del self._attr()[index]
+ return item
+ except IndexError:
+ raise ItemNotFoundError(index)
+
+ @handler(u'Remove all items (use with care).')
+ def clear(self):
+ if isinstance(self._attr(), dict):
+ self._attr.clear()
+ else:
+ self._attr(list())
+
+ @handler(u'Get information about an item')
+ def get(self, index):
+ r"get(index) -> item :: List all the information of an item."
+ if not isinstance(self._attr(), dict):
+ index = int(index) # TODO validation
+ try:
+ return self._vattr()[index]
+ except IndexError:
+ raise ItemNotFoundError(index)
+
+ @handler(u'Get information about all items')
+ def show(self):
+ r"show() -> list of items :: List all the complete items information."
+ if isinstance(self._attr(), dict):
+ return self._attr().values()
+ return self._vattr()
+
+class ListSubHandler(ContainerSubHandler):
+ r"""ListSubHandler(parent) -> ListSubHandler instance.
+
+ This is a helper class to inherit from to automatically handle subcommands
+ that operates over a list parent attribute.
+
+ The list attribute to handle and the class of objects that it contains can
+ be defined by calling the constructor or in a more declarative way as
+ class attributes, like:
+
+ class TestHandler(ListSubHandler):
+ _cont_subhandler_attr = 'some_list'
+ _cont_subhandler_class = SomeClass
+
+ This way, the parent's some_list attribute (self.parent.some_list) will be
+ managed automatically, providing the commands: add, update, delete, get,
+ list and show. New items will be instances of SomeClass, which should
+ provide a cmp operator to see if the item is on the list and an update()
+ method, if it should be possible to modify it. If SomeClass has an _add,
+ _update or _delete attribute, it set them to true when the item is added,
+ updated or deleted respectively (in case that it's deleted, it's not
+ removed from the list, but it's not listed either).
+ """
+
+ @handler(u'Get how many items are in the list')
+ def len(self):
+ r"len() -> int :: Get how many items are in the list."
+ return len(self._vattr())
+
+class DictSubHandler(ContainerSubHandler):
+ r"""DictSubHandler(parent) -> DictSubHandler instance.
+
+ This is a helper class to inherit from to automatically handle subcommands
+ that operates over a dict parent attribute.
+
+ The dict attribute to handle and the class of objects that it contains can
+ be defined by calling the constructor or in a more declarative way as
+ class attributes, like:
+
+ class TestHandler(DictSubHandler):
+ _cont_subhandler_attr = 'some_dict'
+ _cont_subhandler_class = SomeClass
+
+ This way, the parent's some_dict attribute (self.parent.some_dict) will be
+ managed automatically, providing the commands: add, update, delete, get,
+ list and show. New items will be instances of SomeClass, which should
+ provide a constructor with at least the key value, an as_tuple() method
+ and an update() method, if it should be possible to modify
+ it. If SomeClass has an _add, _update or _delete attribute, it set
+ them to true when the item is added, updated or deleted respectively
+ (in case that it's deleted, it's not removed from the dict, but it's
+ not listed either).
+ """
+
+ @handler(u'List all the items by key')
+ def list(self):
+ r"list() -> tuple :: List all the item keys."
+ return self._attr().keys()
+