Pythonic solution for conditional arguments passing

后端 未结 9 797
无人共我
无人共我 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条回答
  •  梦毁少年i
    2020-12-29 21:01

    If you don't want to change anything in func then the sensible option would be passing a dict of arguments to the function:

    >>> def func(a=0,b=10):
    ...  return a+b
    ...
    >>> args = {'a':15,'b':15}
    >>> func(**args)
    30
    >>> args={'a':15}
    >>> func(**args)
    25
    >>> args={'b':6}
    >>> func(**args)
    6
    >>> args = {}
    >>> func(**args)
    10
    

    or just:

    >>>func(**{'a':7})
    17
    

提交回复
热议问题