Why does *args argument unpacking give a tuple?

前端 未结 3 1568
孤城傲影
孤城傲影 2021-01-06 10:03

In python, it is possible to define a function taking an arbitrary number of positional arguments like so:

def f(*args):
    print(args)
f(1, 2, 3)  # (1, 2,         


        
3条回答
  •  别那么骄傲
    2021-01-06 10:35

    My best guess would be that if *args generates a list(mutable), it can lead to very surprising results for a multitude of situations. @Ondrej K. has given a great example. As an analogy, when having a list as a default argument, every function call might have different default arguments. This is the result of default arguments being evaluated only once, and this situation is not the most intuitive. Even the official python docs have a specific workaround for this exact situation.

    Default parameter values are evaluated from left to right when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same “pre-computed” value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use None as the default, and explicitly test for it in the body of the function, e.g.:

    def whats_on_the_telly(penguin=None):
    if penguin is None:
        penguin = []
    penguin.append("property of the zoo")
    return penguin
    

    Source documentation

    To summarize, I believe that *args is a tuple because having it as a list would cause all the problems associated with a mutable type (like slower speed) and the bigger issue would be that most do not expect function arguments to change. Although I do agree that this implementation is very inconsistent with PEP-3132 and will cause confusion for most learners. I am very new to Python and it took me a while to understand what might be the reason for *args to be a tuple and not a list for the sake of consistency with PEP-3132's acceptance.

提交回复
热议问题