What is the difference in *args, **kwargs vs calling with tuple and dict? [duplicate]

空扰寡人 提交于 2019-12-14 00:01:42

问题


This is a basic question. Is there a difference in doing

def foo(*args, **kwargs):
    """standard function that accepts variable length."""
    # do something

foo(v1...vn, nv1=nv1...nvn=nvn)

def foo(arg, kwargs):
    """convention, call with tuple and dict."""
    # do something

mytuple = (v1, ..vn)
mydict = {nv1=nv1, ...nvn=nvn}
foo(mytuple, mydict)

I could do the same thing with both, except that the later has a weird convention of creating a tuple and dictionary. But basically is there a difference? I can solve the same computational problem of handling infinite things because dict and tuple can take care of that for me anyway?

Is this more of an idiomatic part of Python i.e a good Syntactic Sugar for things that you do anyway? I.e function is going to handle this for you!

PS: Not sure of so many downvotes though I agree this is a copy of Why use packed *args/**kwargs instead of passing list/dict? and probably it should be corrected in the duplicate information. And that question has recieved upvotes. So am I being downvotes for not being able to find that?


回答1:


args and kwargs are just names.
What really matters here is the * and **.

In your second example you can only call the function with 2 arguments, against the first example where you can call the function with basically infinite arguments.



来源:https://stackoverflow.com/questions/37112721/what-is-the-difference-in-args-kwargs-vs-calling-with-tuple-and-dict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!