Call function without optional arguments if they are None

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

    I'm surprised nobody brought this up

    def f(p1="foo", p2=None):
        p2 = "bar" if p2 is None else p2
        print(p1+p2)
    

    You assign None to p2 as standart (or don't, but this way you have the true standart at one point in your code) and use an inline if. Imo the most pythonic answer. Another thing that comes to mind is using a wrapper, but that would be way less readable.

    EDIT: What I'd probably do is use a dummy as standart value and check for that. So something like this:

    class dummy():
        pass
    
    def alpha(p1="foo", p2=dummy()):
        if isinstance(p2, dummy):
            p2 = "bar"
        print("{0},{1}".format(p1, p2))
    
    alpha()
    alpha("a","b")
    alpha(p2=None)
    

    produces:

    foo,bar
    a,b
    foo,None
    

提交回复
热议问题