Source

graphalchemy / graphalchemy / mixins / collections.py

Full commit
# -*- coding: utf-8 -*-
'''graph element collections'''

from stuf.utils import lazy

from graphalchemy.core import octopus

__all__ = ('LinksMixin', 'NodesMixin')


class _CollectionMixin(octopus.context.Thing):

    '''element collection'''

    def __init__(self, this=None, model=None, **kw):
        '''
        init

        @param this: graph element (default: None)
        @param model: graph model (default: None)
        '''
        super(_CollectionMixin, self).__init__()
        self._this = this
        self._model = model
        self.direction = kw.get('direction', None)

    def __getitem__(self, key):
        return self._inner[key]

    def __delitem__(self, key):
        self[key].delete()

    def __iter__(self):
        for item in self._inner:
            yield item

    def __len__(self):
        return len(self)

    def __repr__(self):
        return str(self._inner)

    def deep_dump(self):
        '''deep serializeable form of graph elements in this collection'''
        return [n.deep_dump() for n in self]

    def dump(self):
        '''serializeable form of graph elements in this collection'''
        return [n.dump() for n in self]


class LinksMixin(_CollectionMixin):

    '''links collection'''

    @lazy
    def _inner(self):
        return self._this.l.walked(self._this, self.direction)


class NodesMixin(_CollectionMixin):

    '''nodes collection'''

    def __init__(self, this=None, model=None, **kw):
        '''
        init

        @param this: graph element (default: None)
        @param model: graph model (default: None)
        '''
        super(NodesMixin, self).__init__(this, model, **kw)
        # node property keys to search for
        self.keys = kw.pop('keys', ())
        # which node end to return
        self.link_end = kw.pop('link_end', 'end')

    @lazy
    def _inner(self):
        return self._this.n.walked(
            self._this, self.direction, keys=self.keys, end=self.link_end,
        )