Pythonic solution for conditional arguments passing

后端 未结 9 798
无人共我
无人共我 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:12

    You can add a decorator that would eliminate None arguments:

    def skip_nones(fun):
        def _(*args, **kwargs):
            for a, v in zip(fun.__code__.co_varnames, args):
                if v is not None:
                    kwargs[a] = v
            return fun(**kwargs)
        return _
    
    @skip_nones
    def func(a=10, b=20):
        print a, b
    
    func(None, None) # 10 20
    func(11, None)   # 11 20
    func(None, 33)   # 10 33
    

提交回复
热议问题