1

是否有一个Iterable对象可以持有的钩子/dunder,以便可以将内置filter函数扩展到Iterable类(不仅仅是实例)?

当然,也可以写一个自定义filter_iter函数,比如:

def filter_iter(filt_func: callable, collection_cls: type):
    name = 'Filtered' + collection_cls.__name__  # would this automatic scheme lead to namespace conflicts?
    wrapped_cls = type(name, (collection_cls,), {'_filt_func': staticmethod(filt_func)})
    def __iter__(self):
        yield from filter(self._filt_func, super(wrapped_cls, self).__iter__())
    wrapped_cls.__iter__ = __iter__
    return wrapped_cls

这将产生预期的效果。例如,

from collections import Collection, Iterable
class Chunker(Iterable):
    def __init__(self, source: Iterable, chk_size: int=2):
        self._source = source
        self._chk_size = chk_size
    def __iter__(self):
        yield from zip(*([iter(self._source)] * self._chk_size))


chunker = Chunker(range(12), 2)
assert list(chunker) == [(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
FilteredChunker = filter_iter(lambda x: sum(x) % 3 == 0, Chunker)
filtered_chunker = FilteredChunker(range(12))
assert list(filtered_chunker) == [(4, 5), (10, 11)]

但是,就像有一个__iter__钩子可以确定如何迭代一个对象(例如,list在对象上调用时应该如何表现),是否有一种__filter__钩子可以确定filter在该对象上调用时应该如何表现?

如果没有,围绕过滤迭代的最佳实践或标准是什么?

4

1 回答 1

0

list__iter__例如)不同,没有这样的钩子filter。后者只是迭代器协议的一个应用,它本身并不是一个单独的协议。

为了不让你空手而归,这里是 filtered_iter你提出的更简洁的版本,它动态地继承给定的类,__iter__filter.

def filter_iter(p, cls):
    class _(cls):
        def __iter__(self):
            yield from filter(p, super().__iter__())
    return _
于 2020-05-25T14:06:41.137 回答