File: filter.py

package info (click to toggle)
python-picklable-itertools 0.1.1-2
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 172 kB
  • sloc: python: 1,222; makefile: 3
file content (71 lines) | stat: -rw-r--r-- 2,002 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
from abc import ABCMeta, abstractmethod
import six
from .iter_dispatch import iter_
from .base import BaseItertool


@six.add_metaclass(ABCMeta)
class BaseFilter(BaseItertool):
    def __init__(self, pred, seq):
        self._predicate = pred
        self._iter = iter_(seq)

    @abstractmethod
    def __next__(self):
        pass


class ifilter(BaseFilter):
    """ifilter(function or None, iterable) --> ifilter object

    Return an iterator yielding those items of iterable for which
    function(item) is true. If function is None, return the items that are
    true.
    """

    def _keep(self, value):
        predicate = bool if self._predicate is None else self._predicate
        return predicate(value)

    def __next__(self):
        val = next(self._iter)
        while not self._keep(val):
            val = next(self._iter)
        return val


class ifilterfalse(ifilter):
    """ifilterfalse(function or None, sequence) --> ifilterfalse object

    Return those items of sequence for which function(item) is false.
    If function is None, return the items that are false.
    """
    def _keep(self, value):
        return not super(ifilterfalse, self)._keep(value)


class takewhile(BaseFilter):
    """takewhile(predicate, iterable) --> takewhile object

    Return successive entries from an iterable as long as the
    predicate evaluates to true for each entry.
    """
    def __next__(self):
        value = next(self._iter)
        if not self._predicate(value):
            raise StopIteration
        return value


class dropwhile(takewhile):
    """dropwhile(predicate, iterable) --> dropwhile object

    Drop items from the iterable while predicate(item) is true.
    Afterwards, return every element until the iterable is exhausted.
    """
    def __next__(self):
        value = next(self._iter)
        while not getattr(self, '_started', False) and self._predicate(value):
            value = next(self._iter)
        self._started = True
        return value