Call function without optional arguments if they are None

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

    I had the same problem when calling some Swagger generated client code, which I couldn't modify, where None could end up in the query string if I didn't clean up the arguments before calling the generated methods. I ended up creating a simple helper function:

    def defined_kwargs(**kwargs):
        return {k: v for k, v in kwargs.items() if v is not None}
    
    >>> alpha(**defined_kwargs(p1="FOO", p2=None))
    FOO,bar
    

    It keeps things quite readable for more complex invocations:

    def beta(a, b, p1="foo", p2="bar"):
         print('{0},{1},{2},{3}'.format(a, b, p1, p2,))
    
    p1_value = "foo"
    p2_value = None
    
    >>> beta("hello",
             "world",
             **defined_kwargs(
                 p1=p1_value, 
                 p2=p2_value))
    
    hello,world,FOO,bar
    

提交回复
热议问题