Python collections.abc() Examples

The following are code examples for showing how to use collections.abc(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: web_ctp   Author: molebot   File: test_dict.py    (license) View Source Project 6 votes vote down vote up
def test_itemiterator_pickling(self):
        data = {1:"a", 2:"b", 3:"c"}
        # dictviews aren't picklable, only their iterators
        itorg = iter(data.items())
        d = pickle.dumps(itorg)
        it = pickle.loads(d)
        # note that the type of type of the unpickled iterator
        # is not necessarily the same as the original.  It is
        # merely an object supporting the iterator protocol, yielding
        # the same objects as the original one.
        # self.assertEqual(type(itorg), type(it))
        #self.assertTrue(isinstance(it, collections.abc.Iterator))
        self.assertEqual(dict(it), data)

        it = pickle.loads(d)
        drop = next(it)
        d = pickle.dumps(it)
        it = pickle.loads(d)
        del data[drop[0]]
        self.assertEqual(dict(it), data) 
Example 2
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_union(self):
        u = self.s.union(self.otherword)
        for c in self.letters:
            self.assertEqual(c in u, c in self.d or c in self.otherword)
        self.assertEqual(self.s, self.thetype(self.word))
        self.assertEqual(type(u), self.basetype)
        self.assertRaises(PassThru, self.s.union, check_pass_thru())
        self.assertRaises(TypeError, self.s.union, [[]])
        for C in set, frozenset, dict.fromkeys, str, list, tuple:
            self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd'))
            self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg'))
            self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc'))
            self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef'))
            self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg'))

        # Issue #6573
        x = self.thetype()
        self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2])) 
Example 3
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_iterator_pickling(self):
        itorg = iter(self.s)
        data = self.thetype(self.s)
        d = pickle.dumps(itorg)
        it = pickle.loads(d)
        # Set iterators unpickle as list iterators due to the
        # undefined order of set items.
        # self.assertEqual(type(itorg), type(it))
        self.assertTrue(isinstance(it, collections.abc.Iterator))
        self.assertEqual(self.thetype(it), data)

        it = pickle.loads(d)
        try:
            drop = next(it)
        except StopIteration:
            return
        d = pickle.dumps(it)
        it = pickle.loads(d)
        self.assertEqual(self.thetype(it), data - self.thetype((drop,))) 
Example 4
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_update(self):
        retval = self.s.update(self.otherword)
        self.assertEqual(retval, None)
        for c in (self.word + self.otherword):
            self.assertIn(c, self.s)
        self.assertRaises(PassThru, self.s.update, check_pass_thru())
        self.assertRaises(TypeError, self.s.update, [[]])
        for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.update(C(p)), None)
                self.assertEqual(s, set(q))
        for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
            q = 'ahi'
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.update(C(p), C(q)), None)
                self.assertEqual(s, set(s) | set(p) | set(q)) 
Example 5
Project: web_ctp   Author: molebot   File: test_iter.py    (license) View Source Project 6 votes vote down vote up
def check_pickle(self, itorg, seq):
        d = pickle.dumps(itorg)
        it = pickle.loads(d)
        # Cannot assert type equality because dict iterators unpickle as list
        # iterators.
        # self.assertEqual(type(itorg), type(it))
        self.assertTrue(isinstance(it, collections.abc.Iterator))
        self.assertEqual(list(it), seq)

        it = pickle.loads(d)
        try:
            next(it)
        except StopIteration:
            return
        d = pickle.dumps(it)
        it = pickle.loads(d)
        self.assertEqual(list(it), seq[1:])

    # Test basic use of iter() function 
Example 6
Project: ouroboros   Author: pybee   File: test_dict.py    (license) View Source Project 6 votes vote down vote up
def test_itemiterator_pickling(self):
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            data = {1:"a", 2:"b", 3:"c"}
            # dictviews aren't picklable, only their iterators
            itorg = iter(data.items())
            d = pickle.dumps(itorg, proto)
            it = pickle.loads(d)
            # note that the type of type of the unpickled iterator
            # is not necessarily the same as the original.  It is
            # merely an object supporting the iterator protocol, yielding
            # the same objects as the original one.
            # self.assertEqual(type(itorg), type(it))
            self.assertIsInstance(it, collections.abc.Iterator)
            self.assertEqual(dict(it), data)

            it = pickle.loads(d)
            drop = next(it)
            d = pickle.dumps(it, proto)
            it = pickle.loads(d)
            del data[drop[0]]
            self.assertEqual(dict(it), data) 
Example 7
Project: ouroboros   Author: pybee   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_union(self):
        u = self.s.union(self.otherword)
        for c in self.letters:
            self.assertEqual(c in u, c in self.d or c in self.otherword)
        self.assertEqual(self.s, self.thetype(self.word))
        self.assertEqual(type(u), self.basetype)
        self.assertRaises(PassThru, self.s.union, check_pass_thru())
        self.assertRaises(TypeError, self.s.union, [[]])
        for C in set, frozenset, dict.fromkeys, str, list, tuple:
            self.assertEqual(self.thetype('abcba').union(C('cdc')), set('abcd'))
            self.assertEqual(self.thetype('abcba').union(C('efgfe')), set('abcefg'))
            self.assertEqual(self.thetype('abcba').union(C('ccb')), set('abc'))
            self.assertEqual(self.thetype('abcba').union(C('ef')), set('abcef'))
            self.assertEqual(self.thetype('abcba').union(C('ef'), C('fg')), set('abcefg'))

        # Issue #6573
        x = self.thetype()
        self.assertEqual(x.union(set([1]), x, set([2])), self.thetype([1, 2])) 
Example 8
Project: ouroboros   Author: pybee   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_iterator_pickling(self):
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            itorg = iter(self.s)
            data = self.thetype(self.s)
            d = pickle.dumps(itorg, proto)
            it = pickle.loads(d)
            # Set iterators unpickle as list iterators due to the
            # undefined order of set items.
            # self.assertEqual(type(itorg), type(it))
            self.assertIsInstance(it, collections.abc.Iterator)
            self.assertEqual(self.thetype(it), data)

            it = pickle.loads(d)
            try:
                drop = next(it)
            except StopIteration:
                continue
            d = pickle.dumps(it, proto)
            it = pickle.loads(d)
            self.assertEqual(self.thetype(it), data - self.thetype((drop,))) 
Example 9
Project: ouroboros   Author: pybee   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_update(self):
        retval = self.s.update(self.otherword)
        self.assertEqual(retval, None)
        for c in (self.word + self.otherword):
            self.assertIn(c, self.s)
        self.assertRaises(PassThru, self.s.update, check_pass_thru())
        self.assertRaises(TypeError, self.s.update, [[]])
        for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.update(C(p)), None)
                self.assertEqual(s, set(q))
        for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
            q = 'ahi'
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.update(C(p), C(q)), None)
                self.assertEqual(s, set(s) | set(p) | set(q)) 
Example 10
Project: ouroboros   Author: pybee   File: test_iter.py    (license) View Source Project 6 votes vote down vote up
def check_pickle(self, itorg, seq):
        for proto in range(pickle.HIGHEST_PROTOCOL + 1):
            d = pickle.dumps(itorg, proto)
            it = pickle.loads(d)
            # Cannot assert type equality because dict iterators unpickle as list
            # iterators.
            # self.assertEqual(type(itorg), type(it))
            self.assertTrue(isinstance(it, collections.abc.Iterator))
            self.assertEqual(list(it), seq)

            it = pickle.loads(d)
            try:
                next(it)
            except StopIteration:
                continue
            d = pickle.dumps(it, proto)
            it = pickle.loads(d)
            self.assertEqual(list(it), seq[1:])

    # Test basic use of iter() function 
Example 11
Project: presentations   Author: MarneeDear   File: hello-world.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 12
Project: presentations   Author: MarneeDear   File: rop.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 13
Project: presentations   Author: MarneeDear   File: rop_decorated.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 14
Project: presentations   Author: MarneeDear   File: factorial.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 15
Project: presentations   Author: MarneeDear   File: lamba_partial.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 16
Project: presentations   Author: MarneeDear   File: common.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 17
Project: presentations   Author: MarneeDear   File: quick_sort.py    (license) View Source Project 6 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    elif not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        else:
            return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    elif index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    elif (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    else:
        return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 18
Project: presentations   Author: MarneeDear   File: quick_sort.py    (license) View Source Project 6 votes vote down vote up
def quick_sort(*_coconut_match_to_args, **_coconut_match_to_kwargs):
    _coconut_match_check = False
    if (_coconut.len(_coconut_match_to_args) == 1) and (_coconut.isinstance(_coconut_match_to_args[0], _coconut.abc.Sequence)) and (_coconut.len(_coconut_match_to_args[0]) >= 1):
        tail = _coconut.list(_coconut_match_to_args[0][1:])
        head = _coconut_match_to_args[0][0]
        if (not _coconut_match_to_kwargs):
            _coconut_match_check = True
    if not _coconut_match_check:
        _coconut_match_err = _coconut_MatchError("pattern-matching failed for " "'def quick_sort([head] + tail) ='" " in " + _coconut.repr(_coconut.repr(_coconut_match_to_args)))
        _coconut_match_err.pattern = 'def quick_sort([head] + tail) ='
        _coconut_match_err.value = _coconut_match_to_args
        raise _coconut_match_err

    """Sort the input sequence using the quick sort algorithm."""
    return (quick_sort([x for x in tail if x < head]) + [head] + quick_sort([x for x in tail if x >= head]))

# Test cases: 
Example 19
Project: kbe_server   Author: xiaohaoppy   File: test_dict.py    (license) View Source Project 6 votes vote down vote up
def test_itemiterator_pickling(self):
        data = {1:"a", 2:"b", 3:"c"}
        # dictviews aren't picklable, only their iterators
        itorg = iter(data.items())
        d = pickle.dumps(itorg)
        it = pickle.loads(d)
        # note that the type of type of the unpickled iterator
        # is not necessarily the same as the original.  It is
        # merely an object supporting the iterator protocol, yielding
        # the same objects as the original one.
        # self.assertEqual(type(itorg), type(it))
        self.assertTrue(isinstance(it, collections.abc.Iterator))
        self.assertEqual(dict(it), data)

        it = pickle.loads(d)
        drop = next(it)
        d = pickle.dumps(it)
        it = pickle.loads(d)
        del data[drop[0]]
        self.assertEqual(dict(it), data) 
Example 20
Project: kbe_server   Author: xiaohaoppy   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_iterator_pickling(self):
        itorg = iter(self.s)
        data = self.thetype(self.s)
        d = pickle.dumps(itorg)
        it = pickle.loads(d)
        # Set iterators unpickle as list iterators due to the
        # undefined order of set items.
        # self.assertEqual(type(itorg), type(it))
        self.assertTrue(isinstance(it, collections.abc.Iterator))
        self.assertEqual(self.thetype(it), data)

        it = pickle.loads(d)
        try:
            drop = next(it)
        except StopIteration:
            return
        d = pickle.dumps(it)
        it = pickle.loads(d)
        self.assertEqual(self.thetype(it), data - self.thetype((drop,))) 
Example 21
Project: kbe_server   Author: xiaohaoppy   File: test_set.py    (license) View Source Project 6 votes vote down vote up
def test_update(self):
        retval = self.s.update(self.otherword)
        self.assertEqual(retval, None)
        for c in (self.word + self.otherword):
            self.assertIn(c, self.s)
        self.assertRaises(PassThru, self.s.update, check_pass_thru())
        self.assertRaises(TypeError, self.s.update, [[]])
        for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.update(C(p)), None)
                self.assertEqual(s, set(q))
        for p in ('cdc', 'efgfe', 'ccb', 'ef', 'abcda'):
            q = 'ahi'
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.update(C(p), C(q)), None)
                self.assertEqual(s, set(s) | set(p) | set(q)) 
Example 22
Project: kbe_server   Author: xiaohaoppy   File: test_iter.py    (license) View Source Project 6 votes vote down vote up
def check_pickle(self, itorg, seq):
        d = pickle.dumps(itorg)
        it = pickle.loads(d)
        # Cannot assert type equality because dict iterators unpickle as list
        # iterators.
        # self.assertEqual(type(itorg), type(it))
        self.assertTrue(isinstance(it, collections.abc.Iterator))
        self.assertEqual(list(it), seq)

        it = pickle.loads(d)
        try:
            next(it)
        except StopIteration:
            return
        d = pickle.dumps(it)
        it = pickle.loads(d)
        self.assertEqual(list(it), seq[1:])

    # Test basic use of iter() function 
Example 23
Project: SoS   Author: vatlab   File: utils.py    (license) View Source Project 6 votes vote down vote up
def stable_repr(obj):
    if isinstance(obj, str):
        return repr(obj)
    elif isinstance(obj, collections.abc.Mapping):
        items = [stable_repr(k) + ':' + stable_repr(obj[k]) for k in obj.keys()]
        return '{' + ', '.join(sorted(items)) + '}'
    elif isinstance(obj, collections.abc.Set):
        items = [stable_repr(x) for x in obj]
        return '{' + ', '.join(sorted(items)) + '}'
    elif isinstance(obj, collections.abc.Sequence):
        return '[' + ', '.join(stable_repr(k) for k in obj) + ']'
    else:
        return repr(obj)

#
# A utility function that returns output of a command 
Example 24
Project: notebooks   Author: fluentpython   File: strkeydict2.py    (license) View Source Project 5 votes vote down vote up
def update(self, iterable=None, **kwds):
        if iterable is not None:
            if isinstance(iterable, collections.abc.Mapping):  # <5>
                pairs = iterable.items()
            else:
                pairs = ((k, v) for k, v in iterable)  # <6>
            for key, value in pairs:
                self[key] = value  # <7>
        if kwds:
            self.update(kwds)  # <8>

# END STRKEYDICT 
Example 25
Project: ribosome   Author: tek   File: __coconut__.py    (license) View Source Project 5 votes vote down vote up
def _coconut_igetitem(iterable, index):
    if isinstance(iterable, (_coconut_reversed, _coconut_map, _coconut.filter, _coconut.zip, _coconut_enumerate, _coconut_count, _coconut.abc.Sequence)):
        return iterable[index]
    if not _coconut.isinstance(index, _coconut.slice):
        if index < 0:
            return _coconut.collections.deque(iterable, maxlen=-index)[0]
        return _coconut.next(_coconut.itertools.islice(iterable, index, index + 1))
    if index.start is not None and index.start < 0 and (index.stop is None or index.stop < 0) and index.step is None:
        queue = _coconut.collections.deque(iterable, maxlen=-index.start)
        if index.stop is not None:
            queue = _coconut.tuple(queue)[:index.stop - index.start]
        return queue
    if (index.start is not None and index.start < 0) or (index.stop is not None and index.stop < 0) or (index.step is not None and index.step < 0):
        return _coconut.tuple(iterable)[index]
    return _coconut.itertools.islice(iterable, index.start, index.stop, index.step) 
Example 26
Project: ribosome   Author: tek   File: __coconut__.py    (license) View Source Project 5 votes vote down vote up
def tee(iterable, n=2):
    if n >= 0 and _coconut.isinstance(iterable, (_coconut.tuple, _coconut.frozenset)):
        return (iterable,) * n
    if n > 0 and (_coconut.hasattr(iterable, "__copy__") or _coconut.isinstance(iterable, _coconut.abc.Sequence)):
        return (iterable,) + _coconut.tuple(_coconut.copy.copy(iterable) for _ in _coconut.range(n - 1))
    return _coconut.itertools.tee(iterable, n) 
Example 27
Project: ribosome   Author: tek   File: __coconut__.py    (license) View Source Project 5 votes vote down vote up
def fmap(func, obj):
    """fmap(func, obj) creates a copy of obj with func applied to its contents.
    Override by defining .__fmap__(func)."""
    if _coconut.hasattr(obj, "__fmap__"):
        return obj.__fmap__(func)
    args = _coconut_starmap(func, obj.items()) if _coconut.isinstance(obj, _coconut.abc.Mapping) else _coconut_map(func, obj)
    if _coconut.isinstance(obj, _coconut.tuple) and _coconut.hasattr(obj, "_make"):
        return obj._make(args)
    if _coconut.isinstance(obj, (_coconut.map, _coconut.range, _coconut.abc.Iterator)):
        return args
    if _coconut.isinstance(obj, _coconut.str):
        return "".join(args)
    return obj.__class__(args) 
Example 28
Project: Udacity_Robotics_cs373   Author: lijiyao111   File: utils.py    (license) View Source Project 5 votes vote down vote up
def sequence(iterable):
    "Coerce iterable to sequence, if it is not already one."
    return (iterable if isinstance(iterable, collections.abc.Sequence)
            else tuple(iterable)) 
Example 29
Project: Udacity_Robotics_cs373   Author: lijiyao111   File: utils.py    (license) View Source Project 5 votes vote down vote up
def issequence(x):
    "Is x a sequence?"
    return isinstance(x, collections.abc.Sequence) 
Example 30
Project: python3-utils   Author: soldni   File: core.py    (license) View Source Project 5 votes vote down vote up
def is_list_or_tuple(obj):
    """Returns True if obj is a list or a tuple"""
    return (
        isinstance(obj, collections.abc.Sequence) and
        not(isinstance(obj, str) or isinstance(obj, bytes))
    ) 
Example 31
Project: Udacity_AIND_Planning   Author: TilakD   File: utils.py    (license) View Source Project 5 votes vote down vote up
def sequence(iterable):
    "Coerce iterable to sequence, if it is not already one."
    return (iterable if isinstance(iterable, collections.abc.Sequence)
            else tuple(iterable)) 
Example 32
Project: Udacity_AIND_Planning   Author: TilakD   File: utils.py    (license) View Source Project 5 votes vote down vote up
def issequence(x):
    "Is x a sequence?"
    return isinstance(x, collections.abc.Sequence) 
Example 33
Project: metapensiero.reactive   Author: azazel75   File: stream_utils.py    (license) View Source Project 5 votes vote down vote up
def get_agen(self, factory):
        self.check_source()
        if isinstance(factory, collections.abc.AsyncIterable):
            result = factory.__aiter__()
        else:
            result = factory()
        assert isinstance(result, collections.abc.AsyncGenerator)
        return result 
Example 34
Project: metapensiero.reactive   Author: azazel75   File: stream_utils.py    (license) View Source Project 5 votes vote down vote up
def source(self, value):
        if value is self._source:
            return
        if self.active:
            raise RuntimeError("Cannot set the source while active")
        if not (isinstance(value, collections.abc.AsyncIterable) or
                callable(value)):
            raise RuntimeError("The source must be and async iterable or a "
                               "callable returning an async generator")
        self._source = value 
Example 35
Project: py-aspio   Author: hexhex   File: input.py    (license) View Source Project 5 votes vote down vote up
def get_collection_iterator(self, context: Context) -> Iterator[Any]:
        collection = self._accessor.perform_access(context)
        if isinstance(collection, collections.abc.Set):  # type: ignore (mypy does not know about collections.abc)
            return iter(collection)
        elif isinstance(collection, collections.abc.Sequence):  # type: ignore (mypy does not know about collections.abc)
            return enumerate(collection)  # yields (index, element) tuples
        elif isinstance(collection, collections.abc.Mapping):  # type: ignore (mypy does not know about collections.abc)
            return iter(collection.items())  # yields (key, element) tuples
        else:
            raise ValueError(
                'During iteration {0!r}: '
                'collection object of type {1!r} could not be identified as Set, Sequence or Dictionary. '
                'It should inherit from collections.abc.Set, collections.abc.Sequence, or collections.abc.Mapping.'
                .format(self, type(collection))) 
Example 36
Project: web_ctp   Author: molebot   File: test_dict.py    (license) View Source Project 5 votes vote down vote up
def test_pop(self):
        # Tests for pop with specified key
        d = {}
        k, v = 'abc', 'def'
        d[k] = v
        self.assertRaises(KeyError, d.pop, 'ghi')

        self.assertEqual(d.pop(k), v)
        self.assertEqual(len(d), 0)

        self.assertRaises(KeyError, d.pop, k)

        self.assertEqual(d.pop(k, v), v)
        d[k] = v
        self.assertEqual(d.pop(k, 1), v)

        self.assertRaises(TypeError, d.pop)

        class Exc(Exception): pass

        class BadHash(object):
            fail = False
            def __hash__(self):
                if self.fail:
                    raise Exc()
                else:
                    return 42

        x = BadHash()
        d[x] = 42
        x.fail = True
        self.assertRaises(Exc, d.pop, x) 
Example 37
Project: web_ctp   Author: molebot   File: test_collections.py    (license) View Source Project 5 votes vote down vote up
def test_factory(self):
        Point = namedtuple('Point', 'x y')
        self.assertEqual(Point.__name__, 'Point')
        self.assertEqual(Point.__slots__, ())
        self.assertEqual(Point.__module__, __name__)
        self.assertEqual(Point.__getitem__, tuple.__getitem__)
        self.assertEqual(Point._fields, ('x', 'y'))
        self.assertIn('class Point(tuple)', Point._source)

        self.assertRaises(ValueError, namedtuple, 'abc%', 'efg ghi')       # type has non-alpha char
        self.assertRaises(ValueError, namedtuple, 'class', 'efg ghi')      # type has keyword
        self.assertRaises(ValueError, namedtuple, '9abc', 'efg ghi')       # type starts with digit

        self.assertRaises(ValueError, namedtuple, 'abc', 'efg g%hi')       # field with non-alpha char
        self.assertRaises(ValueError, namedtuple, 'abc', 'abc class')      # field has keyword
        self.assertRaises(ValueError, namedtuple, 'abc', '8efg 9ghi')      # field starts with digit
        self.assertRaises(ValueError, namedtuple, 'abc', '_efg ghi')       # field with leading underscore
        self.assertRaises(ValueError, namedtuple, 'abc', 'efg efg ghi')    # duplicate field

        namedtuple('Point0', 'x1 y2')   # Verify that numbers are allowed in names
        namedtuple('_', 'a b c')        # Test leading underscores in a typename

        nt = namedtuple('nt', 'the quick brown fox')                       # check unicode input
        self.assertNotIn("u'", repr(nt._fields))
        nt = namedtuple('nt', ('the', 'quick'))                           # check unicode input
        self.assertNotIn("u'", repr(nt._fields))

        self.assertRaises(TypeError, Point._make, [11])                     # catch too few args
        self.assertRaises(TypeError, Point._make, [11, 22, 33])             # catch too many args 
Example 38
Project: web_ctp   Author: molebot   File: test_collections.py    (license) View Source Project 5 votes vote down vote up
def validate_abstract_methods(self, abc, *names):
        methodstubs = dict.fromkeys(names, lambda s, *args: 0)

        # everything should work will all required methods are present
        C = type('C', (abc,), methodstubs)
        C()

        # instantiation should fail if a required method is missing
        for name in names:
            stubs = methodstubs.copy()
            del stubs[name]
            C = type('C', (abc,), stubs)
            self.assertRaises(TypeError, C, name) 
Example 39
Project: web_ctp   Author: molebot   File: test_collections.py    (license) View Source Project 5 votes vote down vote up
def validate_isinstance(self, abc, name):
        stub = lambda s, *args: 0

        C = type('C', (object,), {'__hash__': None})
        setattr(C, name, stub)
        self.assertIsInstance(C(), abc)
        self.assertTrue(issubclass(C, abc))

        C = type('C', (object,), {'__hash__': None})
        self.assertNotIsInstance(C(), abc)
        self.assertFalse(issubclass(C, abc)) 
Example 40
Project: web_ctp   Author: molebot   File: test_collections.py    (license) View Source Project 5 votes vote down vote up
def test_repr_recursive(self):
        # See issue #9826
        od = OrderedDict.fromkeys('abc')
        od['x'] = od
        self.assertEqual(repr(od),
            "OrderedDict([('a', None), ('b', None), ('c', None), ('x', ...)])") 
Example 41
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 5 votes vote down vote up
def test_difference(self):
        i = self.s.difference(self.otherword)
        for c in self.letters:
            self.assertEqual(c in i, c in self.d and c not in self.otherword)
        self.assertEqual(self.s, self.thetype(self.word))
        self.assertEqual(type(i), self.basetype)
        self.assertRaises(PassThru, self.s.difference, check_pass_thru())
        self.assertRaises(TypeError, self.s.difference, [[]])
        for C in set, frozenset, dict.fromkeys, str, list, tuple:
            self.assertEqual(self.thetype('abcba').difference(C('cdc')), set('ab'))
            self.assertEqual(self.thetype('abcba').difference(C('efgfe')), set('abc'))
            self.assertEqual(self.thetype('abcba').difference(C('ccb')), set('a'))
            self.assertEqual(self.thetype('abcba').difference(C('ef')), set('abc'))
            self.assertEqual(self.thetype('abcba').difference(), set('abc'))
            self.assertEqual(self.thetype('abcba').difference(C('a'), C('b')), set('c')) 
Example 42
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 5 votes vote down vote up
def test_sub_and_super(self):
        p, q, r = map(self.thetype, ['ab', 'abcde', 'def'])
        self.assertTrue(p < q)
        self.assertTrue(p <= q)
        self.assertTrue(q <= q)
        self.assertTrue(q > p)
        self.assertTrue(q >= p)
        self.assertFalse(q < r)
        self.assertFalse(q <= r)
        self.assertFalse(q > r)
        self.assertFalse(q >= r)
        self.assertTrue(set('a').issubset('abc'))
        self.assertTrue(set('abc').issuperset('a'))
        self.assertFalse(set('a').issubset('cbs'))
        self.assertFalse(set('cbs').issuperset('a')) 
Example 43
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 5 votes vote down vote up
def test_difference_update(self):
        retval = self.s.difference_update(self.otherword)
        self.assertEqual(retval, None)
        for c in (self.word + self.otherword):
            if c in self.word and c not in self.otherword:
                self.assertIn(c, self.s)
            else:
                self.assertNotIn(c, self.s)
        self.assertRaises(PassThru, self.s.difference_update, check_pass_thru())
        self.assertRaises(TypeError, self.s.difference_update, [[]])
        self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
        for p, q in (('cdc', 'ab'), ('efgfe', 'abc'), ('ccb', 'a'), ('ef', 'abc')):
            for C in set, frozenset, dict.fromkeys, str, list, tuple:
                s = self.thetype('abcba')
                self.assertEqual(s.difference_update(C(p)), None)
                self.assertEqual(s, set(q))

                s = self.thetype('abcdefghih')
                s.difference_update()
                self.assertEqual(s, self.thetype('abcdefghih'))

                s = self.thetype('abcdefghih')
                s.difference_update(C('aba'))
                self.assertEqual(s, self.thetype('cdefghih'))

                s = self.thetype('abcdefghih')
                s.difference_update(C('cdc'), C('aba'))
                self.assertEqual(s, self.thetype('efghih')) 
Example 44
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 5 votes vote down vote up
def test_add_present(self):
        self.set.add("c")
        self.assertEqual(self.set, set("abc")) 
Example 45
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 5 votes vote down vote up
def test_discard_absent(self):
        self.set.discard("d")
        self.assertEqual(self.set, set("abc")) 
Example 46
Project: web_ctp   Author: molebot   File: test_set.py    (license) View Source Project 5 votes vote down vote up
def setUp(self):
        self.set   = set((1, 2, 3))
        self.other = 'abc'
        self.otherIsIterable = True

#------------------------------------------------------------------------------ 
Example 47
Project: web_ctp   Author: molebot   File: test_iter.py    (license) View Source Project 5 votes vote down vote up
def test_builtin_tuple(self):
        self.assertEqual(tuple(SequenceClass(5)), (0, 1, 2, 3, 4))
        self.assertEqual(tuple(SequenceClass(0)), ())
        self.assertEqual(tuple([]), ())
        self.assertEqual(tuple(()), ())
        self.assertEqual(tuple("abc"), ("a", "b", "c"))

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(tuple(d), tuple(d.keys()))

        self.assertRaises(TypeError, tuple, list)
        self.assertRaises(TypeError, tuple, 42)

        f = open(TESTFN, "w")
        try:
            for i in range(5):
                f.write("%d\n" % i)
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            self.assertEqual(tuple(f), ("0\n", "1\n", "2\n", "3\n", "4\n"))
            f.seek(0, 0)
            self.assertEqual(tuple(f),
                             ("0\n", "1\n", "2\n", "3\n", "4\n"))
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass

    # Test filter()'s use of iterators. 
Example 48
Project: web_ctp   Author: molebot   File: test_iter.py    (license) View Source Project 5 votes vote down vote up
def test_in_and_not_in(self):
        for sc5 in IteratingSequenceClass(5), SequenceClass(5):
            for i in range(5):
                self.assertIn(i, sc5)
            for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5:
                self.assertNotIn(i, sc5)

        self.assertRaises(TypeError, lambda: 3 in 12)
        self.assertRaises(TypeError, lambda: 3 not in map)

        d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
        for k in d:
            self.assertIn(k, d)
            self.assertNotIn(k, d.values())
        for v in d.values():
            self.assertIn(v, d.values())
            self.assertNotIn(v, d)
        for k, v in d.items():
            self.assertIn((k, v), d.items())
            self.assertNotIn((v, k), d.items())

        f = open(TESTFN, "w")
        try:
            f.write("a\n" "b\n" "c\n")
        finally:
            f.close()
        f = open(TESTFN, "r")
        try:
            for chunk in "abc":
                f.seek(0, 0)
                self.assertNotIn(chunk, f)
                f.seek(0, 0)
                self.assertIn((chunk + "\n"), f)
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass

    # Test iterators with operator.countOf (PySequence_Count). 
Example 49
Project: sublimeTextConfig   Author: luoye-fe   File: typing.py    (license) View Source Project 5 votes vote down vote up
def __instancecheck__(self, obj):
        # For unparametrized Callable we allow this, because
        # typing.Callable should be equivalent to
        # collections.abc.Callable.
        if self.__args__ is None and self.__result__ is None:
            return isinstance(obj, collections_abc.Callable)
        else:
            raise TypeError("Callable[] cannot be used with isinstance().") 
Example 50
Project: python-telegram-dialog-bot   Author: Saluev   File: bot.py    (license) View Source Project 5 votes vote down vote up
def send_answer(self, bot, chat_id, answer):
        print("Sending answer %r to %s" % (answer, chat_id))
        if isinstance(answer, collections.abc.Iterable) and not isinstance(answer, str):
            # ?? ???????? ????????? ???????? -- ?????? ?????? ???? ??????????
            answer = list(map(self._convert_answer_part, answer))
        else:
            # ?? ???????? ???? ?????? -- ?????? ? ????? ????? ??????
            answer = [self._convert_answer_part(answer)]
        # ????? ???, ??? ????????? ????????? ?????????, ???? ?????? ? ???????
        # «????????» -- ?????????? ??? ??? ? ??????????? ??? ????-??????
        current_message = last_message = None
        for part in answer:
            if isinstance(part, Message):
                if current_message is not None:
                    # ?????????, ??????? ?? ????????? ??????, ???? ?? ?????????.
                    # ????????? ?? ??? ??????? ?????????, ????? ??? ?????????
                    # ?? ???????? ???????? (???? ?? ??????? ????????)
                    current_message = copy.deepcopy(current_message)
                    current_message.options.setdefault("disable_notification", True)
                    self._send_or_edit(bot, chat_id, current_message)
                current_message = part
            if isinstance(part, ReplyMarkup):
                # ???, ? ??? ? ???????! ????????? ???????? ?????????.
                # ??? ????????? -- ?? ????????, ??? ??????.
                current_message.options["reply_markup"] = part
        # ???? ?? ?????? ????????? ????????? ??????????? ?????????.
        if current_message is not None:
            self._send_or_edit(bot, chat_id, current_message)