Conditionally passing arbitrary number of default named arguments to a function

前端 未结 4 1822
情书的邮戳
情书的邮戳 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条回答
  •  没有蜡笔的小新
    2020-12-19 00:12

    You can write a helper function

    def caller(func, *args, **kwargs):
        return func(*args, **{k:v for k,v in kwargs.items() if v != caller.DONT_PASS})
    caller.DONT_PASS = object()
    

    Use this function to call another function and use caller.DONT_PASS to specify arguments that you don't want to pass.

    caller(func, 'arg', 'arg2', arg3 = 'some value' if condition else caller.DONT_PASS)
    

    Note that this caller() only support conditionally passing keyword arguments. To support positional arguments, you may need to use module inspect to inspect the function.

提交回复
热议问题