Pythonic solution for conditional arguments passing

后端 未结 9 785
无人共我
无人共我 2020-12-29 20:24

I have a function with two optional parameters:

def func(a=0, b=10):
    return a+b

Somewhere else in my code I am doing some conditional a

9条回答
  •  既然无缘
    2020-12-29 20:59

    to solve your specific question I would do:

    args = {'a' : a, 'b' : b}
    for varName, varVal in args.items():
        if not varVal:
            del args[varName]
    f(**args)
    

    But the most pythonic way would be to use None as the default value in your function:

    f(a=None, b=None):
        a = 10 if a is None else a
        ...
    

    and just call f(a, b)

提交回复
热议问题