0

Given the following function, what is the meaning of the unused second (*) parameter?

def callback(arg, *, kwarg='default'):
    print('my arg: {}, my kwarg: {}'.format(arg, kwarg))

I'm familiar with *arg and **kwarg which inevitably comes up when trying to Google the above's meaning.

(The example is modified from The Python Standard Library by Example book.)

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Zach Cleary
  • 458
  • 1
  • 4
  • 17
  • 2
    It means everything after it have to be used as `named arguments`... eg... `callback('whatever')` will work... but to change the `kwarg` argument you *have to explicitly use* `callback('whatever', kwarg='something else')` - you can't do `callback('whatever', 'something else')` – Jon Clements Aug 19 '18 at 09:35
  • What is the value in forcing the use of explicit named arguments, particularly in such a simple example? – Zach Cleary Aug 19 '18 at 09:56
  • 1
    You wouldn't want to in simple cases... but where there's potentially quite a lot of 'em and they don't really have a logical order as to be positional arguments with defaults, then it makes it explicit and less error prone to force the caller to name the arguments... Might be worth having a look at [PEP-3102](https://legacy.python.org/dev/peps/pep-3102/) – Jon Clements Aug 19 '18 at 10:02
  • For instance - one case it could come in handy (but can't now because of historical reasons) is `re.sub`... one gotcha that comes up fairly often is people passing in what they think is the *flags* - `re.sub(rx, repl, text, re.I)` but that last position is the number of replacements to make so the call should be `re.sub(rx, repl, text, flags=re.I)` (and since `re.I` is an integer - it can sometimes appear to work just fine depending on what the flags are as the number of replacements happens to be less than it... it can break later though when more...)... – Jon Clements Aug 19 '18 at 10:06
  • Were it `re.sub(rx, repl, text, *, n=None, flags=None)` or something - it'd stop people falling into that gotcha... – Jon Clements Aug 19 '18 at 10:07

0 Answers0