Skip to main content

A Python library providing cacheable iterator wrappers for both synchronous and asynchronous iterators.

Project description

cached-iterators

A Python library providing cacheable iterator wrappers for both synchronous and asynchronous iterators. This allows iterators to be reused multiple times with cached values, reducing the need for recomputations.

Features

  • Reusable Iterators: Wrap synchronous and asynchronous iterators to allow them to be iterated multiple times with cached results.
  • Lazy Loading: Only fetch and cache results as needed, avoiding unnecessary computations or I/O operations.
  • Ease of Use: Simple API with decorators for easy integration.
  • Improved Concurrency: Efficiently handle concurrent tasks that need to use the same iterator.

Installation

You can install this package via pip:

python3 -m pip install cached-iterators

Usage

Synchronous Iterator Wrapper

You can use the synchronous iterator wrapper in two ways: by decorating a function that returns an iterator or by directly wrapping an iterator instance.

  1. Decorating a function:
from cached_iterators import cacheable_iterator
from typing import Iterator


@cacheable_iterator
def generate_numbers() -> Iterator[int]:
  for i in range(5):
    print(f"Generating {i}")
    yield i


# Create a cacheable iterator using the decorated function
cached_iter = generate_numbers()

# First iteration (values will be generated and cached)
print("First iteration:")
for num in cached_iter:
  print(num)

# Second iteration (values will be retrieved from cache)
print("Second iteration:")
for num in cached_iter:
  print(num)
  1. Wrapping an existing iterator:
from cached_iterators import CacheableIteratorWrapper
from typing import Iterator


def generate_numbers() -> Iterator[int]:
  for i in range(5):
    print(f"Generating {i}")
    yield i


# Create a cacheable iterator by wrapping an existing iterator instance
iterator = generate_numbers()
cached_iter = CacheableIteratorWrapper(iterator)

# First iteration (values will be generated and cached)
print("First iteration:")
for num in cached_iter:
  print(num)

# Second iteration (values will be retrieved from cache)
print("Second iteration:")
for num in cached_iter:
  print(num)

Output

First iteration:
Generating 0
0
Generating 1
1
Generating 2
2
Generating 3
3
Generating 4
4
Second iteration:
0
1
2
3
4

Asynchronous Iterator Wrapper

Similarly, the asynchronous iterator wrapper can be used by decorating a function that returns an asynchronous iterator or by directly wrapping an asynchronous iterator instance.

  1. Decorating a function:
import asyncio
from cached_iterators import cacheable_async_iterator
from typing import AsyncIterator


@cacheable_async_iterator
async def async_generate_numbers() -> AsyncIterator[int]:
  for i in range(5):
    print(f"Generating {i}")
    yield i
    await asyncio.sleep(0)  # Simulate async work


# Create a cacheable async iterator using the decorated function
cached_iter = async_generate_numbers()


async def main():
  # First iteration (values will be generated and cached)
  print("First iteration:")
  async for num in cached_iter:
    print(num)

  # Second iteration (values will be retrieved from cache)
  print("Second iteration:")
  async for num in cached_iter:
    print(num)


# Run the example
asyncio.run(main())
  1. Wrapping an existing iterator:
import asyncio
from cached_iterators import CacheableAsyncIteratorWrapper
from typing import AsyncIterator


async def async_generate_numbers() -> AsyncIterator[int]:
  for i in range(5):
    print(f"Generating {i}")
    yield i
    await asyncio.sleep(0)  # Simulate async work


# Create a cacheable async iterator by wrapping an existing async iterator instance
iterator = async_generate_numbers()
cached_iter = CacheableAsyncIteratorWrapper(iterator)


async def main():
  # First iteration (values will be generated and cached)
  print("First iteration:")
  async for num in cached_iter:
    print(num)

  # Second iteration (values will be retrieved from cache)
  print("Second iteration:")
  async for num in cached_iter:
    print(num)


# Run the example
asyncio.run(main())

Output

First iteration:
Generating 0
0
Generating 1
1
Generating 2
2
Generating 3
3
Generating 4
4
Second iteration:
0
1
2
3
4

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

cached_iterators-1.0.1.tar.gz (3.3 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cached_iterators-1.0.1-py3-none-any.whl (4.8 kB view details)

Uploaded Python 3

File details

Details for the file cached_iterators-1.0.1.tar.gz.

File metadata

  • Download URL: cached_iterators-1.0.1.tar.gz
  • Upload date:
  • Size: 3.3 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.11.6 Darwin/24.0.0

File hashes

Hashes for cached_iterators-1.0.1.tar.gz
Algorithm Hash digest
SHA256 1630ff9d7157262cce2779783d449af889b0fc249c898847acdf7cd24fcb2d2e
MD5 f7cf137ed0273c25e4401c7285788ce5
BLAKE2b-256 cf17f2a0d3ae3e9a21a7cdc7d53a02aa819f84e5676abdddb3ef4880e94296ce

See more details on using hashes here.

File details

Details for the file cached_iterators-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: cached_iterators-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 4.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/1.7.1 CPython/3.11.6 Darwin/24.0.0

File hashes

Hashes for cached_iterators-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 b1b6cb2471caa46dfd1ed3eab8e5df67fcd0cf9fc4fcc21ece0051ee1af10f7b
MD5 c433576727fae7ed56f26d3948937cb9
BLAKE2b-256 173ca6a5a19730bf500fa13387de25b744414af0d5d3bc9f00d4efc95107aea1

See more details on using hashes here.

Supported by

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