Search code examples
pythonparametersarguments

What does * mean as a parameter in python?


I was browsing through this file of code and then I found this class:

class StreamPlaylistEntry(BasePlaylistEntry):
def __init__(self, playlist, url, title, *, destination=None, **meta):
    super().__init__()

I know that an asterisk in front of a parameter means it's a list of an arbitrary number of arguments, but what does the asterisk by itself mean?


Solution

  • It means all arguments afterwards are keyword-only. As said in the official glossary under the word parameter:

    • keyword-only: specifies an argument that can be supplied only by keyword. Keyword-only parameters can be defined by including a single var-positional parameter or bare * in the parameter list of the function definition before them, for example kw_only1 and kw_only2 in the following:

       def func(arg, *, kw_only1, kw_only2): ...
      

    This allows you to force the users of your code (which may include yourself) to be more explicit. Compare:

    def f(x, y, allow_zero=True, some_other_flag=False, bonus=0): ...
    
    f(2, 0, False, True, 100)  # valid
    f(2, 0, allow_zero=False, some_other_flag=True, bonus=100)  # valid
    

    with

    def f(x, y, *, allow_zero=True, some_other_flag=False, bonus=0): ...
    
    f(2, 0, False, True, 100)  # TypeError: f() takes 2 positional arguments but 5 were given
    f(2, 0, allow_zero=False, some_other_flag=True, bonus=100)  # valid