Skip to main content

Chainable lazy iterators

Project description

chainit

Documentation available here: https://lukapeschke.github.io/chainit/

This library provides the ChainIt class, a wrapper around stdlib's itertools module, allowing to chain operations on iterables, resulting in easier-to-read code.

import typing as t

def fib() -> t.Iterable[int]:
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Allows to write things like this...
(
    ChainIt(fib())
    .filter(lambda x: x % 2 == 0)
    .map(lambda x: x // 2)
    .flat_map(range)
    .take_while(lambda x: x < 6)
    .collect_list()
)

# ...rather than like this
from itertools import chain as ichain, islice, takewhile

list(
    takewhile(
        lambda x: x < 6,
        ichain.from_iterable(
            map(lambda x: range(x // 2), filter(lambda x: x % 2 == 0, fib()))
        ),
    )
)

Installation

pip install chainit

Examples

Decorator

In addition to ChainIt, the library provides a chainit decorator. It makes a function returning an iterable return a ChainIt instead:

@chainit
def fac():
    n = 0
    fac = 1
    while True:
        yield fac
        n += 1
        fac *= n

assert fac().enumerate().take(5).collect() == ((0, 1), (1, 1), (2, 2), (3, 6), (4, 24))

Using a ChainIt instance as an iterable

assert list(fac().take(3)) == [1, 1, 2]

for idx, x in fac().enumerate():
    if idx > 3:
        break
    print(x)

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chainit-0.3.0.tar.gz (4.5 kB view hashes)

Uploaded Source

Built Distribution

chainit-0.3.0-py3-none-any.whl (5.6 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page