Call function without optional arguments if they are None

前端 未结 9 2037
自闭症患者
自闭症患者 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:21

    You could inspect the default values via alpha.__defaults__ and then use them instead of None. That way you circumvent the hard-coding of default values:

    >>> args = [None]
    >>> alpha('FOO', *[x if x is not None else y for x, y in zip(args, alpha.__defaults__[1:])])
    

提交回复
热议问题