Thursday, February 23, 2017

Python streams

I've become really comfortable with Java 8's streams over the past couple years.  As a result, when I go back and do Python work, I get stream envy.  I looked around and found a couple options, but none of them were really what I'm after... something quick and dirty that will just make my syntax a bit more readable.

So I threw this together and find it quite handy.  I hope you find it helpful as well.  If you save this to a module and name it 'streams.py', you can use it like the following:

    from lazy_streams import stream

    S = stream(range(250)) \
        .filter(lambda x: (x%2 == 0))
    print S.size()
    print S.take(10).to_string()
    print S.reverse().take(10).to_list()
    S1 = S.map(lambda x: "Item %d" % x)
    print S1.first_or_else('Nothing to see')
    print stream(['Patty Cake', 'Jim Shoe', 'Justin Case']) \
        .sort(lambda x: x.split(' ')[1]) \
        .to_list()
    print stream([[1, 2], 3, [4, 5, 6], 'seven']) \
        .flatten() \
        .to_list()

I've tested it on lists as big as 2.5 million items and the lazy evaluation seems to work really great!

Here's the gist: