Skip to content

AsyncExecutor

Base classes

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

⋔ Inheritance diagram

graph TD
  719587554["async_executor.AsyncExecutor"]
  3481597255["typing.Generic"]
  2751680898["builtins.object"]
  3481597255 --> 719587554
  2751680898 --> 3481597255

🛈 DocStrings

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

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

    def __init__(self, func: Callable[..., Awaitable[T]], *, is_bound: bool) -> None:
        self._func = func
        self._instance: Any = None
        self._is_bound = is_bound
        # Initialize observer system
        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) -> AsyncExecutor[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) -> T:
        """Async call - normal behavior."""
        if self._instance is not None and self._is_bound:
            # We're bound to an instance, prepend it to args
            result = await self._func(self._instance, *args, **kwargs)
        else:
            result = await self._func(*args, **kwargs)

        # Emit to all observers
        if self._observers:
            await self._observers.call_handlers(self._observer_mode, result)

        return result

    def sync(self, *args: P.args, **kwargs: P.kwargs) -> T:
        """Synchronous version using asyncio.run or thread pool."""
        coro = self(*args, **kwargs)

        try:
            # Check if we're already in an async context
            asyncio.get_running_loop()
        except RuntimeError:
            # No running loop, safe to use asyncio.run
            return asyncio.run(coro)
        else:
            # We're in an async context, fall back to thread pool
            warnings.warn(
                "Calling .sync() from async context - using thread pool. "
                "Consider using 'await' instead for better performance.",
                UserWarning,
                stacklevel=2,
            )

            def run_coro() -> T:
                return asyncio.run(coro)

            with ThreadPoolExecutor() as executor:
                return executor.submit(run_coro).result()

    def task(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[T]:
        """Create a Task for concurrent execution."""
        return asyncio.create_task(self(*args, **kwargs))

    def submit(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[T]:
        """Fire-and-forget execution, returns Task but doesn't need to be awaited."""
        return _keep_alive(self.task(*args, **kwargs))

    async def timeout(self, timeout_sec: float, *args: P.args, **kwargs: P.kwargs) -> T:
        """Call with timeout."""
        return await asyncio.wait_for(self(*args, **kwargs), timeout_sec)

    def connect(self, handler: Callable[[T], Any]) -> None:
        """Add observer that will be called with the function's return value."""
        self._observers.add_handler(handler)

    def disconnect(self, handler: Callable[[T], Any]) -> None:
        """Remove observer."""
        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) -> T

Async call - normal behavior.

Source code in src/anyenv/calling/async_executor.py
async def __call__(self, *args: P.args, **kwargs: P.kwargs) -> T:
    """Async call - normal behavior."""
    if self._instance is not None and self._is_bound:
        # We're bound to an instance, prepend it to args
        result = await self._func(self._instance, *args, **kwargs)
    else:
        result = await self._func(*args, **kwargs)

    # Emit to all observers
    if self._observers:
        await self._observers.call_handlers(self._observer_mode, result)

    return result

__get__

__get__(instance: Any, owner: type | None = None) -> AsyncExecutor[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) -> AsyncExecutor[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]) -> None

Add observer that will be called with the function's return value.

Source code in src/anyenv/calling/async_executor.py
def connect(self, handler: Callable[[T], Any]) -> None:
    """Add observer that will be called with the function's return value."""
    self._observers.add_handler(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."""
    self._observers.remove_handler(handler)

submit

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

Fire-and-forget execution, returns Task but doesn't need to be awaited.

Source code in src/anyenv/calling/async_executor.py
def submit(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[T]:
    """Fire-and-forget execution, returns Task but doesn't need to be awaited."""
    return _keep_alive(self.task(*args, **kwargs))

sync

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

Synchronous version using asyncio.run or thread pool.

Source code in src/anyenv/calling/async_executor.py
def sync(self, *args: P.args, **kwargs: P.kwargs) -> T:
    """Synchronous version using asyncio.run or thread pool."""
    coro = self(*args, **kwargs)

    try:
        # Check if we're already in an async context
        asyncio.get_running_loop()
    except RuntimeError:
        # No running loop, safe to use asyncio.run
        return asyncio.run(coro)
    else:
        # We're in an async context, fall back to thread pool
        warnings.warn(
            "Calling .sync() from async context - using thread pool. "
            "Consider using 'await' instead for better performance.",
            UserWarning,
            stacklevel=2,
        )

        def run_coro() -> T:
            return asyncio.run(coro)

        with ThreadPoolExecutor() as executor:
            return executor.submit(run_coro).result()

task

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

Create a Task for concurrent execution.

Source code in src/anyenv/calling/async_executor.py
def task(self, *args: P.args, **kwargs: P.kwargs) -> asyncio.Task[T]:
    """Create a Task for concurrent execution."""
    return asyncio.create_task(self(*args, **kwargs))

timeout async

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

Call with timeout.

Source code in src/anyenv/calling/async_executor.py
async def timeout(self, timeout_sec: float, *args: P.args, **kwargs: P.kwargs) -> T:
    """Call with timeout."""
    return await asyncio.wait_for(self(*args, **kwargs), timeout_sec)

:fa-brands-github: Show source on GitHub