Call function without optional arguments if they are None

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

    But assume that alpha is used in other places where it is actually supposed to handle None as it does.

    To respond to this concern, I have been known to have a None-like value which isn't actually None for this exact purpose.

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

    Now the arguments are still optional, so you can neglect to pass either of them. And the function handles None correctly. If you ever want to explicitly not pass an argument, you can pass _novalue.

    >>> alpha(p1="FOO", p2=None)
    FOO,None
    >>> alpha(p1="FOO")
    FOO,bar
    >>> alpha(p1="FOO", p2=_novalue)
    FOO,bar
    

    and since _novalue is a special made-up value created for this express purpose, anyone who passes _novalue is certainly intending the "default argument" behavior, as opposed to someone who passes None who might intend that the value be interpreted as literal None.

提交回复
热议问题