11

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?

6harat
  • 542
  • 6
  • 18

1 Answers1

26

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

Chris
  • 29,127
  • 3
  • 28
  • 51