Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does * represent in function argument list in python? [duplicate]

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?

like image 740
6harat Avatar asked Dec 17 '22 16:12

6harat


1 Answers

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

like image 88
Chris Avatar answered Dec 28 '22 11:12

Chris