khaz
khaz

Reputation: 417

How to use all of these: *args, **kwargs, "*" and "/"

I was practicing with different function signatures and wanted to try a function with all of these: positional and key-word arguments, with variable number of those, along with specifying positional- keyword- arguments only.

I got thus far:

def fun(a, /, b, *, c=None, **kwargs):
    print(f"{a = }, {b = }, {c = }")

where a is positional-only argument, b can be either positional or keyword, c is keyword-only argument, and additional keyword arguments are allowed.

However, when I tried to collect additional positional arguments in *args, it resulted in a syntax error. I think all the possible places for *args were tested.

Is it impossible to use all, /, *, *args and *kwargs at the same time? Or perhaps I missed one possibility?

EDIT

On 2023.08.14 an article was published: "What Are Python Asterisk and Slash Special Parameters For?" (Real Python)

Upvotes: 1

Views: 473

Answers (1)

deceze
deceze

Reputation: 522081

def foo(a, *args, b)

Here a is positional, args soaks up any additional positional arguments, and b is a keyword parameter. There is absolutely no point in including * here, as its only role is to terminate positional parameters and start keyword parameters. But *args already does that.

You can think of * as *args without args, meaning additional positional arguments will not be soaked up into a parameter. Other than that, * and *args already do the same job. Which makes sense, since they use the same "*".

Upvotes: 3

Related Questions