Why does *args argument unpacking give a tuple?

前端 未结 3 1571
孤城傲影
孤城傲影 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:36

    I don't know if this was the thinking behind it, but that ease of processing (even though instantiate a list with the tuple data is not that hard) would come at possible confusing behavior.

    def fce1(*args):
       fce2(args)
       # some more code using args
    
    def fce2(args):
       args.insert(0, 'other_val')
    
    fce1(1, 2, 3)
    

    Could surprise people writing fce1 code not realizing that args they deal with later on are not what the function was called with.

    I would also presume immutable types are easier to deal with internally and come with less overhead.

提交回复
热议问题