20

While going through the source code, I noticed the following syntax being used in the asyncio library:

@coroutine
def sleep(delay, result=None, *, loop=None):
    """Coroutine that completes after a given time (in seconds)."""
    if delay == 0:
        yield
        return result

    if loop is None:
        loop = events.get_event_loop()
    future = loop.create_future()
    h = future._loop.call_later(delay,
                                futures._set_result_unless_cancelled,
                                future, result)
    try:
        return (yield from future)
    finally:
        h.cancel()

what does the * do in the argument list?

0

1 Answer 1

41

It means that parameter(s) that comes after * are keyword only parameters.

Consider the following:

def test(delay, result=None, *, loop=None):
    print(delay, result, loop)

In this case, test(1,2,2) will raise TypeError since it is expecting at most two positional arguments, i.e. delay and result:

test(1,2,2)

TypeError: test() takes from 1 to 2 positional arguments but 3 were given

The third argument, or loop, can only be assigned if used as keyword:

test(1,2,loop=2)
# 1 2 2
# Works fine

For more detail, refer to Function Definitions

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.