I'm attempting to apply multiple filters and maps to a list and attempted to refactor into something i believe is more readable. In my code, I am reading a file to create a list of terms, then munging it into something I will feed into another script.
Please note my terminology in the title might be wrong, but please feel free to correct.
Originally, I had something that looked like this:
random_substring = lambda word: word[:(random.randrange(len(word) - 2) + 1)]
only_longer_words = lambda word: len(word) > 2
terms = []
#File manipulation that adds words to terms
terms = filter(only_longer_words, terms)
terms = map(random_substring, terms)
terms = filter(only_longer_words, terms)
#Save terms to file
After refactoring, I created a ChainList which inherits from list:
class ChainList(list):
def filter(self, function):
return ChainList(filter(function, self))
def map(self, function):
return ChainList(map(function, self))
def uniquify(self):
return ChainList(OrderedDict.fromkeys(self))
and use it as such:
terms = ChainList()
working_list = (
terms.filter(only_longer_words)
.map(random_substring)
.filter(only_longer_words)
.uniquify()
)
The intent is to make it easy to chain operations on lists. It works, but as a Python beginner, wanted a review.