Passing all arguments of a function to another function

后端 未结 3 961
迷失自我
迷失自我 2020-12-02 21:47

I want to pass all the arguments passed to a function(func1) as arguments to another function(func2) inside func1 This can be done wit

相关标签:
3条回答
  • 2020-12-02 22:23

    Provided that the arguments to func1 are only keyword arguments, you could do this:

    def func1(a=1, b=2, c=3):
        func2(**locals())
    
    0 讨论(0)
  • 2020-12-02 22:28

    As others have said, using locals() might cause you to pass on more variables than intended, if func1() creates new variables before calling func2().

    This is can be circumvented by calling locals() as the first thing, like so:

    def func1(a=1, b=2,c=3):
        par = locals()
    
        d = par["a"] + par["b"]
    
        func2(**par)
    
    0 讨论(0)
  • 2020-12-02 22:30

    Explicit is better than implicit but if you really don't want to type a few characters:

    def func1(a=1, b=2, c=3):
        func2(**locals())
    

    locals() are all local variables, so you can't set any extra vars before calling func2 or they will get passed too.

    0 讨论(0)
提交回复
热议问题