4 ms·
What does * represent here? The "self" object?
by nafey 6y ago
What does * represent here? The "self" object?
- masklinn 6y agoIt‘s a separator between positional and keywords. It’s * because the “rest” argument (*args) also makes following arguments keyword-only, so a lone star is essentially one which collects nothing.
- foota 6y agoSo this requires the following args to be named? Neat!
- masklinn 6y agoYes. For python-level functions initially all arguments could be passed either positionally or by keyword, unless they slotted into the special `∗args` (positional-only) or `∗∗kwargs` (keyword-only) parameters (note: the star-prefixes is the important part here the names can be anything). Now I'm saying this was for python-level functions because (AFAIK) at the C level it was always possible to rather easily define positional-only or keyword-only arguments. Anyway one of the improvements of Python 3 was to allow parameters other than `∗∗kwargs` after `∗args`, with the effect of making them individually named but keyword-only (PEP 3102). A logical extension of the same was to allow keyword-only arguments without any positional, that's what the `*` pseudo-argument defines: > The reasoning behind this change is as follows. Imagine for a moment a function which takes several positional arguments, as well as a keyword argument. > Now, suppose you wanted to have 'key' be a keyword-only argument. Under the above syntax, you could accomplish this by adding a varargs (nb: `∗ignore`) argument immediately before the keyword argument. > Unfortunately, the 'ignore' argument will also suck up any erroneous positional arguments that may have been supplied by the caller. Given that we'd prefer any unwanted arguments to raise an error, we could do this (nb: add an explicit assertion that `ignore` is empty) > As a convenient shortcut, we can simply omit the 'ignore' name, meaning 'don't allow any positional arguments beyond this point'.