Slicerator

1.1.0 · active · verified Thu Apr 16

Slicerator is a Python library that provides a lazy-loading, fancy-sliceable iterable. It allows you to wrap existing classes or functions to make them behave like reusable generators that support advanced slicing (like NumPy arrays), but only load data when explicitly accessed. The current version is 1.1.0, released in April 2022. While releases are not on a strict schedule, it remains a functional and actively used utility in various projects.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@Slicerator.from_class` decorator to turn a regular class with `__getitem__` and `__len__` into a lazy-loading, fancy-sliceable iterable. It highlights that actual data loading (`__getitem__` execution) only occurs when specific items are requested or when the Slicerator is fully iterated.

from slicerator import Slicerator

@Slicerator.from_class
class MyLazyLoader:
    def __getitem__(self, i):
        # This method is wrapped by Slicerator to accept slices, lists of integers, or boolean masks.
        # The code below will only execute when an individual item (integer index) is requested.
        # In a real application, this would load data from disk, a database, or network.
        print(f"[DEBUG] Loading item {i}")
        return f"data_item_{i}"

    def __len__(self):
        # Slicerator needs __len__ for proper slicing (e.g., reverse slicing or knowing slice bounds).
        print("[DEBUG] Calculating total length")
        return 10

# Instantiate the lazy loader
loader = MyLazyLoader()

# Create a Slicerator object by slicing. No data is loaded yet.
sliced_data = loader[::2] # Get every second item
print(f"\nInitial slice created: {sliced_data}")

# Further slice the Slicerator. Still no data loaded.
sub_sliced_data = sliced_data[1:] # Get elements from index 1 onwards of the sliced_data
print(f"Further sliced: {sub_sliced_data}")

# Access a single item - this triggers loading for that specific item.
first_item = sub_sliced_data[0]
print(f"First item accessed: {first_item}")

# Convert to list - this triggers loading for all items in `sub_sliced_data`.
all_items = list(sub_sliced_data)
print(f"All items loaded: {all_items}")

view raw JSON →