将空参数传递给Python函数?

Whi*_*ger 2 python

当我正在调用的函数有很多参数,而且我想要有条件地包含一个函数时,我是否必须对该函数进行两次单独的调用,或者是否有一些东西不通过(几乎就像None)以便我我没有传递任何特定参数的参数?

例如,我想sixth有时传递参数的参数,但有时我想传递该参数的任何内容.这段代码有效,但感觉我复制的次数超出了我的要求.

我正在调用的函数位于第三方库中,因此我无法更改它处理接收参数的方式.如果我通过Nonesixth,将抛出一个异常.我需要通过我'IMPORTANT_VALUE'或不通过任何东西.

我目前在做什么:

def do_a_thing(stuff, special=False):

    if special:
        response = some.library.func(
            first=os.environ['first'],
            second=stuff['second'],
            third=stuff['third']
            fourth='Some Value',
            fifth=False,
            sixth='IMPORTANT_VALUE',
            seventh='example',
            eighth=True
        )
    else:
        response = some.library.func(
            first=os.environ['first'],
            second=stuff['second'],
            third=stuff['third']
            fourth='Some Value',
            fifth=False,
            seventh='example',
            eighth=True
        )

    return response
Run Code Online (Sandbox Code Playgroud)

我想做什么:

def do_a_thing(stuff, special=False):
    special_value = 'IMPORTANT_VALUE' if special else EMPTY_VALUE

    response = some.library.func(
        first=os.environ['first'],
        second=stuff['second'],
        third=stuff['third']
        fourth='Some Value',
        fifth=False,
        sixth=special_value,
        seventh='example',
        eighth=True
    )

    return response
Run Code Online (Sandbox Code Playgroud)

Ant*_*ane 5

一种解决方案可能是使用要传递给函数的值构建一个dict,并根据special值进行修改.然后使用python unpacking将其展开为要调用的函数的命名参数列表:

def do_a_thing(stuff, special=False):

    kwargs = dict(
        first=os.environ['first'],
        second=stuff['second'],
        third=stuff['third']
        fourth='Some Value',
        fifth=False,
        seventh='example',
        eighth=True
    )

    if special:
        kwargs['sixth'] = 'IMPORTANT_VALUE'

    return some.library.func(**kwargs)
Run Code Online (Sandbox Code Playgroud)