Call function without optional arguments if they are None

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

    Not a direct answer, but I think this is worth considering:

    See if you can break your function into several functions, neither of which has any default arguments. Factor any shared functionality out to a function you designate as internal.

    def alpha():
        _omega('foo', 'bar')
    
    def beta(p1):
        _omega(p1, 'bar')
    
    def _omega(p1, p2):
         print('{0},{1}'.format(p1, p2))
    

    This works well when the extra arguments trigger "extra" functionality, as it may allow you to give the functions more descriptive names.

    Functions with boolean arguments with True and/or False defaults frequently benefit from this type of approach.

提交回复
热议问题