是否有一个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
在该对象上调用时应该如何表现?
如果没有,围绕过滤迭代的最佳实践或标准是什么?