Example #1
0
    def _fields(self, indexes, errors_ok=False):
        """
        Given a tuple of indexes
        Return a 'return_type' containing given indexes of
        the nested seqs in iter(self).

        If errors_ok=True, ignores errors where self
        has asymmetric nested sequences or non-iterable elements.
        """
        # initialize return value with GrepFieldMixin
        rv = make([], GrepFieldMixin)

        # create subsequences containing given indexes
        for elem in self:
            sublist = make([], GrepFieldMixin)
            try:
                for i in indexes:
                    sublist.append(elem[i])
            except Exception, e:
                if errors_ok and \
                        (isinstance(e, TypeError) or isinstance(e, IndexError)):
                    continue
                raise
            #print 'sublist', sublist # debug

            rv.append(sublist)
Example #2
0
    def _grep(self, value, seq, parent):
        """Depth-first search for value in seq and nested-seqs
           Return flattened list of elements containing value.
           if parent=True, return parent seq containing value"""

        # Initialize return value
        rv = make([], GrepFieldMixin)

        for x in seq:
            append = False
            recurse = True

            # Did we find an exact match?
            if value == x:
                append = True
            try:
                # Strings: is val in string?
                match = False
                if isinstance(x, str) and value in x:
                    append = True
                # Match on edge condition
                if len(x) == 1:
                    if isinstance(x, str) and value in x[0] or value == x[0]:
                        x = x[0]
                        append = True
                        recurse = False
            except Exception, e:
                pass # likely not iterable or 'value in x' not possible

            if append:
                if parent:
                    rv.append(seq)
                    break
                else:
                    rv.append(x)
                    continue

            # Recurse over relevant sub-seqs
            if hasattr(x, '__iter__') and recurse:
                rv.extend(self._grep(value, x,  parent))
Example #3
0
def grepfieldable(inst):
    """add mixin to instance"""
    return make(inst, GrepFieldMixin)