Skip to content

AsyncIteratorExecutor

Base classes

Name Children Inherits
Generic
typing
Abstract base class for generic types.

⋔ Inheritance diagram

graph TD
  2128754744["async_executor.AsyncIteratorExecutor"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3481597255 --> 2128754744
  2751680898 --> 3481597255

🛈 DocStrings

Wrapper that provides both async call and sync() methods for async gens.

Source code in src/anyenv/calling/async_executor.py
class AsyncIteratorExecutor[**P, T]:
    """Wrapper that provides both async __call__ and sync() methods for async gens."""

    def __init__(self, func: Callable[..., AsyncIterator[T]], *, is_bound: bool) -> None:
        self._func = func
        self._instance: Any = None
        self._is_bound = is_bound
        # Initialize observer system for each yielded item
        self._observers = MultiEventHandler[Callable[[T], Any]]()
        self._observer_mode: ExecutionMode = "parallel"
        # Track filtered handlers by type for cleanup
        self._filtered_handlers: dict[
            tuple[type, ...] | tuple[str, int],
            list[tuple[Callable[[T], Any], Callable[[Any], Any]]],
        ] = defaultdict(list)
        # Copy function metadata
        wraps(func)(self)

    def __get__(self, instance: Any, owner: type | None = None) -> AsyncIteratorExecutor[P, T]:
        """Descriptor protocol for method binding."""
        if instance is None:
            return self

        # Cache bound instances per object instance to maintain observer state
        cache = _bound_cache(instance)
        cache_key = id(self)
        if cache_key not in cache:
            # Create bound wrapper to track instance
            bound = type(self)(self._func, is_bound=self._is_bound)
            bound._instance = instance  # noqa: SLF001
            # Each bound instance gets its own isolated observer state
            # (observers, observer_mode, and filtered_handlers are already
            # initialized by __init__)
            # setdefault: a thread that got here first wins, all callers share it.
            cache.setdefault(cache_key, bound)

        return cache[cache_key]  # type: ignore[no-any-return]

    async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> AsyncIterator[T]:
        """Return the async iterator with observer emission."""
        if self._instance is not None and self._is_bound:
            # We're bound to an instance, prepend it to args
            async_iter = self._func(self._instance, *args, **kwargs)
        else:
            async_iter = self._func(*args, **kwargs)

        try:
            async for item in async_iter:
                # Emit each item to observers
                if self._observers:
                    await self._observers.call_handlers(self._observer_mode, item)
                yield item
        finally:
            # Closing this wrapper early closes the wrapped generator too.
            if aclose := getattr(async_iter, "aclose", None):
                await aclose()

    def sync(self, *args: P.args, **kwargs: P.kwargs) -> LazyAsyncIterator[T]:
        """Synchronous version that returns a truly lazy iterator.

        The generator runs in a thread with its own event loop, at most a few items
        ahead of the consumer. ``close()`` (or dropping the iterator) stops it.
        """
        if _in_running_loop():
            warnings.warn(
                "Calling .sync() from async context - using a thread. "
                "Consider using 'async for' instead for better performance.",
                UserWarning,
                stacklevel=2,
            )
        return LazyAsyncIterator(lambda: self(*args, **kwargs))

    def task(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[list[T]]:
        """Create a Task that collects all values into a list."""

        async def _collect() -> list[T]:
            return [item async for item in self(*args, **kwargs)]

        return asyncio.create_task(_collect())

    def submit(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[list[T]]:
        """Fire-and-forget execution that collects all values, returns Task."""
        return _keep_alive(self.task(*args, **kwargs))

    async def timeout(self, timeout_sec: float, *args: P.args, **kwargs: P.kwargs) -> list[T]:
        """Collect all values with timeout."""

        async def _collect() -> list[T]:
            return [item async for item in self(*args, **kwargs)]

        return await asyncio.wait_for(_collect(), timeout_sec)

    def connect(
        self,
        handler: Callable[[T], Any],
        *,
        event_filter: Callable[[T], bool] | None = None,
    ) -> None:
        """Add observer that will be called with each yielded item.

        Args:
            handler: The callback function to connect
            event_filter: Optional filter function to selectively handle events
        """
        if event_filter is None:
            self._observers.add_handler(handler)
        else:
            # Create filtered handler wrapper
            async def filtered_handler(event: T) -> Any:
                if event_filter(event):
                    if inspect.iscoroutinefunction(handler):
                        return await handler(event)
                    return handler(event)
                return None

            # Store with a special key for lambda filters
            lambda_key = ("__lambda_filter__", id(event_filter))
            self._filtered_handlers[lambda_key].append((handler, filtered_handler))
            self._observers.add_handler(filtered_handler)

    def disconnect(self, handler: Callable[[T], Any]) -> None:
        """Remove observer."""
        # Check if it's a filtered handler
        found_and_removed = False
        for event_types, handlers_list in list(self._filtered_handlers.items()):
            for i, (original_handler, filtered_handler) in enumerate(handlers_list):
                if original_handler is handler:
                    self._observers.remove_handler(filtered_handler)
                    handlers_list.pop(i)
                    if not handlers_list:
                        del self._filtered_handlers[event_types]
                    found_and_removed = True
                    break
            if found_and_removed:
                break

        if not found_and_removed:
            self._observers.remove_handler(handler)

    def clear_observers(self) -> None:
        """Remove all observers."""
        self._observers.clear()
        self._filtered_handlers.clear()

    @property
    def observer_count(self) -> int:
        """Number of connected observers."""
        return len(self._observers)

    @property
    def observer_mode(self) -> ExecutionMode:
        """Sequential or parallel observer execution."""
        return self._observer_mode

    @observer_mode.setter
    def observer_mode(self, mode: ExecutionMode) -> None:
        self._observer_mode = mode

    def __getitem__[E](self, event_types: type[E] | types.UnionType) -> EventFilteredConnection[E]:
        """Get filtered connection for specific event type(s).

        Args:
            event_types: Single type or union of types to filter for

        Returns:
            EventFilteredConnection that only triggers for matching event types

        Example:
            my_iterator[MyEvent].connect(handler)
            my_iterator[MyEvent | AnotherEvent].connect(handler)
        """
        # Handle union types
        if isinstance(event_types, types.UnionType):
            # Python 3.10+ union syntax: X | Y
            type_tuple = event_types.__args__
        elif get_origin(event_types) is Union:
            # typing.Union syntax: Union[X, Y]
            type_tuple = get_args(event_types)
        else:
            # Single type
            type_tuple = (event_types,)
        return EventFilteredConnection(self, type_tuple)

    def __getattr__(self, name: str) -> Any:
        """Delegate attribute access to the wrapped function."""
        return getattr(self._func, name)

observer_count property

observer_count: int

Number of connected observers.

observer_mode property writable

observer_mode: ExecutionMode

Sequential or parallel observer execution.

__call__ async

__call__(*args: P.args, **kwargs: P.kwargs) -> AsyncIterator[T]

Return the async iterator with observer emission.

Source code in src/anyenv/calling/async_executor.py
async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> AsyncIterator[T]:
    """Return the async iterator with observer emission."""
    if self._instance is not None and self._is_bound:
        # We're bound to an instance, prepend it to args
        async_iter = self._func(self._instance, *args, **kwargs)
    else:
        async_iter = self._func(*args, **kwargs)

    try:
        async for item in async_iter:
            # Emit each item to observers
            if self._observers:
                await self._observers.call_handlers(self._observer_mode, item)
            yield item
    finally:
        # Closing this wrapper early closes the wrapped generator too.
        if aclose := getattr(async_iter, "aclose", None):
            await aclose()

__get__

__get__(instance: Any, owner: type | None = None) -> AsyncIteratorExecutor[P, T]

Descriptor protocol for method binding.

Source code in src/anyenv/calling/async_executor.py
def __get__(self, instance: Any, owner: type | None = None) -> AsyncIteratorExecutor[P, T]:
    """Descriptor protocol for method binding."""
    if instance is None:
        return self

    # Cache bound instances per object instance to maintain observer state
    cache = _bound_cache(instance)
    cache_key = id(self)
    if cache_key not in cache:
        # Create bound wrapper to track instance
        bound = type(self)(self._func, is_bound=self._is_bound)
        bound._instance = instance  # noqa: SLF001
        # Each bound instance gets its own isolated observer state
        # (observers, observer_mode, and filtered_handlers are already
        # initialized by __init__)
        # setdefault: a thread that got here first wins, all callers share it.
        cache.setdefault(cache_key, bound)

    return cache[cache_key]  # type: ignore[no-any-return]

__getattr__

__getattr__(name: str) -> Any

Delegate attribute access to the wrapped function.

Source code in src/anyenv/calling/async_executor.py
def __getattr__(self, name: str) -> Any:
    """Delegate attribute access to the wrapped function."""
    return getattr(self._func, name)

__getitem__

__getitem__(event_types: type[E] | UnionType) -> EventFilteredConnection[E]

Get filtered connection for specific event type(s).

Parameters:

Name Type Description Default
event_types type[E] | UnionType

Single type or union of types to filter for

required

Returns:

Type Description
EventFilteredConnection[E]

EventFilteredConnection that only triggers for matching event types

Example

my_iterator[MyEvent].connect(handler) my_iterator[MyEvent | AnotherEvent].connect(handler)

Source code in src/anyenv/calling/async_executor.py
def __getitem__[E](self, event_types: type[E] | types.UnionType) -> EventFilteredConnection[E]:
    """Get filtered connection for specific event type(s).

    Args:
        event_types: Single type or union of types to filter for

    Returns:
        EventFilteredConnection that only triggers for matching event types

    Example:
        my_iterator[MyEvent].connect(handler)
        my_iterator[MyEvent | AnotherEvent].connect(handler)
    """
    # Handle union types
    if isinstance(event_types, types.UnionType):
        # Python 3.10+ union syntax: X | Y
        type_tuple = event_types.__args__
    elif get_origin(event_types) is Union:
        # typing.Union syntax: Union[X, Y]
        type_tuple = get_args(event_types)
    else:
        # Single type
        type_tuple = (event_types,)
    return EventFilteredConnection(self, type_tuple)

clear_observers

clear_observers() -> None

Remove all observers.

Source code in src/anyenv/calling/async_executor.py
def clear_observers(self) -> None:
    """Remove all observers."""
    self._observers.clear()
    self._filtered_handlers.clear()

connect

connect(
    handler: Callable[[T], Any], *, event_filter: Callable[[T], bool] | None = None
) -> None

Add observer that will be called with each yielded item.

Parameters:

Name Type Description Default
handler Callable[[T], Any]

The callback function to connect

required
event_filter Callable[[T], bool] | None

Optional filter function to selectively handle events

None
Source code in src/anyenv/calling/async_executor.py
def connect(
    self,
    handler: Callable[[T], Any],
    *,
    event_filter: Callable[[T], bool] | None = None,
) -> None:
    """Add observer that will be called with each yielded item.

    Args:
        handler: The callback function to connect
        event_filter: Optional filter function to selectively handle events
    """
    if event_filter is None:
        self._observers.add_handler(handler)
    else:
        # Create filtered handler wrapper
        async def filtered_handler(event: T) -> Any:
            if event_filter(event):
                if inspect.iscoroutinefunction(handler):
                    return await handler(event)
                return handler(event)
            return None

        # Store with a special key for lambda filters
        lambda_key = ("__lambda_filter__", id(event_filter))
        self._filtered_handlers[lambda_key].append((handler, filtered_handler))
        self._observers.add_handler(filtered_handler)

disconnect

disconnect(handler: Callable[[T], Any]) -> None

Remove observer.

Source code in src/anyenv/calling/async_executor.py
def disconnect(self, handler: Callable[[T], Any]) -> None:
    """Remove observer."""
    # Check if it's a filtered handler
    found_and_removed = False
    for event_types, handlers_list in list(self._filtered_handlers.items()):
        for i, (original_handler, filtered_handler) in enumerate(handlers_list):
            if original_handler is handler:
                self._observers.remove_handler(filtered_handler)
                handlers_list.pop(i)
                if not handlers_list:
                    del self._filtered_handlers[event_types]
                found_and_removed = True
                break
        if found_and_removed:
            break

    if not found_and_removed:
        self._observers.remove_handler(handler)

submit

submit(*args: P.args, **kwargs: P.kwargs) -> Task[list[T]]

Fire-and-forget execution that collects all values, returns Task.

Source code in src/anyenv/calling/async_executor.py
def submit(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[list[T]]:
    """Fire-and-forget execution that collects all values, returns Task."""
    return _keep_alive(self.task(*args, **kwargs))

sync

sync(*args: P.args, **kwargs: P.kwargs) -> LazyAsyncIterator[T]

Synchronous version that returns a truly lazy iterator.

The generator runs in a thread with its own event loop, at most a few items ahead of the consumer. close() (or dropping the iterator) stops it.

Source code in src/anyenv/calling/async_executor.py
def sync(self, *args: P.args, **kwargs: P.kwargs) -> LazyAsyncIterator[T]:
    """Synchronous version that returns a truly lazy iterator.

    The generator runs in a thread with its own event loop, at most a few items
    ahead of the consumer. ``close()`` (or dropping the iterator) stops it.
    """
    if _in_running_loop():
        warnings.warn(
            "Calling .sync() from async context - using a thread. "
            "Consider using 'async for' instead for better performance.",
            UserWarning,
            stacklevel=2,
        )
    return LazyAsyncIterator(lambda: self(*args, **kwargs))

task

task(*args: P.args, **kwargs: P.kwargs) -> Task[list[T]]

Create a Task that collects all values into a list.

Source code in src/anyenv/calling/async_executor.py
def task(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[list[T]]:
    """Create a Task that collects all values into a list."""

    async def _collect() -> list[T]:
        return [item async for item in self(*args, **kwargs)]

    return asyncio.create_task(_collect())

timeout async

timeout(timeout_sec: float, *args: P.args, **kwargs: P.kwargs) -> list[T]

Collect all values with timeout.

Source code in src/anyenv/calling/async_executor.py
async def timeout(self, timeout_sec: float, *args: P.args, **kwargs: P.kwargs) -> list[T]:
    """Collect all values with timeout."""

    async def _collect() -> list[T]:
        return [item async for item in self(*args, **kwargs)]

    return await asyncio.wait_for(_collect(), timeout_sec)

:fa-brands-github: Show source on GitHub