pythonasynchronous

Return an empty AsyncIterable from a function


I would like to define a function returning an empty AsyncIterable of a concrete type.

The function will be a part of a base class; derived classes can implement it as necessary but the default behaviour is to return no items to iterate.

Unfortunately there is no convenient "default value" for the concrete type.

The code has to pass mypy's type checking and ideally pylint.

The following attempts do not work:

async def nope() -> AsyncIterable[int]:
    pass  # error: Missing return statement  [empty-body]
# same with plain 'def'
async def nope() -> AsyncIterable[int]:
    return  # error: Return value expected  [return-value]
# same with plain 'def'

(Found at Empty asynchronous iterable function):

async def nope() -> AsyncIterable[int]:
    yield from () # error: "yield from" in async function
def nope() -> AsyncIterable[int]:
    yield from () # error: The return type of a generator function should be "Generator" or one of its supertypes  [misc]

This works for int but there is no suitable default value for my concrete type. Besides, Pylint warns against a constant conditional:

async def nope() -> AsyncIterable[int]:
    if False: yield 1 # W0125: Using a conditional statement with a constant value (using-constant-test)

What is a simple and understandable way to define a function returning an empty async iterable?


Solution

  • One alternative approach is to yield after an unconditional return:

    async def nope() -> AsyncIterable[int]:
        return
        yield
    

    Demo: https://mypy-play.net/?mypy=latest&python=3.12&gist=657740bc62191070286f954a6ed31508