Call function without optional arguments if they are None

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

    although ** is definitely a language feature, it's surely not created for solving this particular problem. Your suggestion works, so does mine. Which one works better depends on the rest of the OP's code. However, there is still no way to write f(x or dont_pass_it_at_all) - blue_note

    Thanks to your great answers, I thought I'd try to do just that:

    # gen.py
    def callWithNonNoneArgs(f, *args, **kwargs):
        kwargsNotNone = {k: v for k, v in kwargs.items() if v is not None}
        return f(*args, **kwargsNotNone)
    

     

    # python interpreter
    >>> import gen
    >>> def alpha(p1="foo", p2="bar"):
    ...     print('{0},{1}'.format(p1,p2))
    ...
    >>> gen.callWithNonNoneArgs(alpha, p1="FOO", p2=None)
    FOO,bar
    >>> def beta(ree, p1="foo", p2="bar"):
    ...     print('{0},{1},{2}'.format(ree,p1,p2))
    ...
    >>> beta('hello', p2="world")
    hello,foo,world
    >>> beta('hello', p2=None)
    hello,foo,None
    >>> gen.callWithNonNoneArgs(beta, 'hello', p2=None)
    hello,foo,bar
    

    This is probably not perfect, but it seems to work: It's a function that you can call with another function and it's arguments, and it applies deceze's answer to filter out the arguments that are None.

提交回复
热议问题