by JoshuaDavid · 3y ago · 0 comments
class WrappedList:
_fns = [map, filter, min, max, all, any, len, list]
def __init__(self, it):
self.it = it
def __getattr__(self, name):
for fn in self._fns:
if name == fn.__name__:
def m(*args, **kwargs):
result = fn(*args, self.it, **kwargs)
if hasattr(result, '__iter__'):
return self.__class__(result)
else:
return result
return m
def unwrap(self):
return self.it
This allows you to do stuff like WrappedList([1, 2, 3, 4]).filter(lambda x: x % 2 == 0).map(lambda x: x * 3).list().unwrap() # [6, 12]
WrappedList([1, 2, 3, 4]).map(lambda x: x >= 5).any() # False
Deciding whether or not this is something you should do, rather than just something you can do, is left as an exercise for the reader. [x * 3 for x in [1, 2, 3, 4] if x % 2 == 0]
with that said, I still love the general concept of chaining, and I use that style a lot where it is already convenient and popular - in pandas code. self._fns = {fn.__name__: fn for fn in [...]}
This may not be faster since the list is so short, but worth checking into