IterableIO: Adapt Generators to File-like Objects

1.0.1 · active · verified Fri Apr 17

iterable-io is a lightweight Python library (current version 1.0.1) that provides an `IterableIO` class to adapt any byte-iterable (like generators, lists, or custom iterators) into a file-like object conforming to the `io.RawIOBase` interface. This allows iterables to be used in contexts expecting file-like objects, such as `zipfile.ZipFile`, `tarfile.TarFile`, or HTTP request bodies. The library is stable with a slow, focused release cadence.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates creating an `IterableIO` from a byte generator and using it directly or wrapping it with `io.TextIOWrapper` for string-based operations.

from iterable_io import IterableIO
import io

# Example 1: Adapting a generator of bytes
def byte_generator():
    yield b"Hello"
    yield b" "
    yield b"World!"

# Create an IterableIO object from the generator
file_like_object = IterableIO(byte_generator())

# Use it like a file
print(f"Read 6 bytes: {file_like_object.read(6).decode()}") # Output: Hello 
print(f"Read remaining: {file_like_object.read().decode()}") # Output: World!

# Example 2: Adapting string data using io.TextIOWrapper
string_data = ["line1\n", "line2\n", "last line"]

# The IterableIO expects bytes, so encode the strings
byte_stream = IterableIO(s.encode('utf-8') for s in string_data)

# Wrap with TextIOWrapper for text operations
text_stream = io.TextIOWrapper(byte_stream, encoding='utf-8')

print(f"First line: {text_stream.readline().strip()}") # Output: line1
print(f"Second line: {text_stream.readline().strip()}") # Output: line2
text_stream.close()

view raw JSON →