I really like Python generators. In particular, I find that they are the right tool for connecting to Rest endpoints - my client code should only iterate on the generator that is associated with the endpoint. However, I find one area where Python generators are not as expressive as we would like. Typically, I need to filter out the data that I get from the endpoint. In my current code, I pass the predicate function to the generator and applies the predicate to the data it processes, and gives only the data if the predicate is True.
I would like to move on to the composition of the generators - for example, data_filter (datasource ()) . Here is some demo code that shows what I tried. It is clear why this does not work, what I'm trying to find out is the most expressive way to solve the problem:
def mock_datasource ():
mock_data = ["sanctuary", "movement", "liberty", "seminar",
"formula","short-circuit", "generate", "comedy"]
for d in mock_data:
yield d
def data_filter (d):
if len(d) < 8:
yield d
for w in (d for d in mock_datasource() if len(d) < 8):
print(w)
source
share