Pythonic solution for conditional arguments passing

后端 未结 9 688
无人共我
无人共我 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 21:04

    You can use the ternary if-then operator to pass conditional arguements into functions https://www.geeksforgeeks.org/ternary-operator-in-python/

    For example, if you want to check if a key actually exists before passing it you can do something like:

     
        def func(arg):
            print(arg)
    
        kwargs = {'name':'Adam')
    
        func( kwargs['name'] if 'name' in kwargs.keys() else '' )       #Expected Output: 'Adam'
        func( kwargs['notakey'] if 'notakey' in kwargs.keys() else '' ) #Expected Output: ''
     
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-29 21:13

    To answer your literal question:

    func(a or 0, b or 10) 
    

    Edit: See comment why this doesn't answer the question.

    0 讨论(0)
提交回复
热议问题