Conditionally passing arbitrary number of default named arguments to a function

前端 未结 4 1816
情书的邮戳
情书的邮戳 2020-12-18 23:58

Is it possible to pass arbitrary number of named default arguments to a Python function conditionally ?

For eg. there\'s a function:

def func(arg, ar         


        
4条回答
  •  猫巷女王i
    2020-12-19 00:27

    If you have a function that has a lot of default arguments

    def lots_of_defaults(arg1 = "foo", arg2 = "bar", arg3 = "baz", arg4 = "blah"):
        pass
    

    and you want to pass different values to some of these, based on something else going on in your program, a simple way is to use ** to unpack a dictionary of argument names and values that you constructed based on your program logic.

    different_than_defaults = {}
    if foobar:
        different_than_defaults["arg1"] = "baaaz"
    if barblah:
        different_than_defaults["arg4"] = "bleck"
    
    lots_of_defaults(**different_than_defaults)
    

    This has the benefit of not clogging up your code at the point of calling your function, if there is a lot of logic determining what goes into your call. You'll need to be carefull if you have any arguments that don't have defaults, to include the values you're passing for those before passing your dictionary.

提交回复
热议问题