pass **kwargs argument to another function with **kwargs

后端 未结 5 1874
青春惊慌失措
青春惊慌失措 2020-11-30 19:06

I do not understand the following example, lets say I have these functions:

# python likes
def save(filename, data, **kwargs):
    fo = openX(filename, \"w\"         


        
5条回答
  •  失恋的感觉
    2020-11-30 19:18

    Expanding on @gecco 's answer, the following is an example that'll show you the difference:

    def foo(**kwargs):
        for entry in kwargs.items():
            print("Key: {}, value: {}".format(entry[0], entry[1]))
    
    # call using normal keys:
    foo(a=1, b=2, c=3)
    # call using an unpacked dictionary:
    foo(**{"a": 1, "b":2, "c":3})
    
    # call using a dictionary fails because the function will think you are
    # giving it a positional argument
    foo({"a": 1, "b": 2, "c": 3})
    # this yields the same error as any other positional argument
    foo(3)
    foo("string")
    
    

    Here you can see how unpacking a dictionary works, and why sending an actual dictionary fails

提交回复
热议问题