Call function without optional arguments if they are None

前端 未结 9 1992
自闭症患者
自闭症患者 2020-12-29 02:00

There\'s a function which takes optional arguments.

def alpha(p1=\"foo\", p2=\"bar\"):
     print(\'{0},{1}\'.format(p1, p2))

Let me iterat

9条回答
  •  一生所求
    2020-12-29 02:13

    Pass the arguments as kwargs from a dictionary, from which you filter out the None values:

    kwargs = dict(p1='FOO', p2=None)
    
    alpha(**{k: v for k, v in kwargs.items() if v is not None})
    

提交回复
热议问题