DEV Community

Mike Lezhnin
Mike Lezhnin

Posted on

3 1

Python Iter class (with proper dot notation)

I realized python has worse generators syntax than javascript/rust/haskell:
instead of something like

my_iterator.filter(cond).map(convert_fn).collect()

in python you have to write

list(map(convert_fn, filter(cond, my_iterator)))

so everything is backwards and much harder to read. As far as I know there is no direct way that would allow one to write that in straight-forward manner.

Hence I made a small python library that fixes that.

It just introduces the Iter class that you can wrap around an iterator and use the chained dot notation, like so:

Iter(my_iterator).filter(cond).map(convert_fn).collect()

I also added first and drop functions, just because they also seem somewhat useful.

The code is quite short, so here you go, maybe you will also find it useful:

import functools

def first(n, it):
    for i, x in enumerate(it):
        if i == n:
            raise StopIteration
        yield x

def drop(n, it):
    for i, x in enumerate(it):
        if i == n-1:
            break
    return it

class Iter:
    def __init__(self, iterable):
        self.it = iter(iterable)
    def __iter__(self):
        return self.it
    def __next__(self):
        return next(self.it)
    def next(self):
        return next(self)
    def map(self, f):
        return Iter(map(f, self))
    def filter(self, cond):
        return Iter(filter(cond, self))
    def reduce(self, f):
        return functools.reduce(f, self)
    def drop(self, n):
        return Iter(drop(n, self))
    def first(self, n):
        return Iter(first(n,self))
    def collect(self):
        return list(self)

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free โ†’

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay