Bare asterisk in function arguments?

后端 未结 6 1295
孤街浪徒
孤街浪徒 2020-11-22 06:22

What does a bare asterisk in the arguments of a function do?

When I looked at the pickle module, I see this:

pickle.dump(obj, file, protocol=None, *,         


        
6条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-22 07:06

    Semantically, it means the arguments following it are keyword-only, so you will get an error if you try to provide an argument without specifying its name. For example:

    >>> def f(a, *, b):
    ...     return a + b
    ...
    >>> f(1, 2)
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: f() takes 1 positional argument but 2 were given
    >>> f(1, b=2)
    3
    

    Pragmatically, it means you have to call the function with a keyword argument. It's usually done when it would be hard to understand the purpose of the argument without the hint given by the argument's name.

    Compare e.g. sorted(nums, reverse=True) vs. if you wrote sorted(nums, True). The latter would be much less readable, so the Python developers chose to make you to write it the former way.

提交回复
热议问题