python - 将空参数传递给 Python 函数?

标签 python

当我调用的函数有很多参数时,我想有条件地包含一个,我是否必须对函数进行两次单独的调用,或者是否有某种方式不传递任何参数(几乎像 None) 这样我就不会为特定参数传递任何参数?

例如,有时我想为参数 sixth 传递参数,但其他时候我想为该参数传递任何内容。这段代码有效,但我感觉我复制的内容超出了我应该复制的范围。

我正在调用的函数位于第三方库中,因此我无法更改它处理接收到的参数的方式。如果我为 sixth 传入 None,该函数会引发异常。我需要传递我的 '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

我想做什么:

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

最佳答案

一个解决方案是构建一个字典,其中包含您要传递给函数的值,并根据 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)

关于python - 将空参数传递给 Python 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48951629/

相关文章:

python - 使用 Blobstore API 和 Images API 在 GAE 中直接从 GCS 提供图像

python - 如何在图像openCV python中找到所有颜色形状

python - 一个类可以包含它自己的一个实例作为数据容器吗?

python - 如何从python中的文本文件中获取 float ?

python - 创建、删除和访问 pandas 数据框中的列

python - 导入给定模块对象的子模块

python - Python中RK4算法错误

python - 为什么 NumPy 为 x[[slice(None), 1, 2]] 创建一个 View

python - 创建类对象时出现类型错误

Windows 7 上的 Python Jedi 漫游文件夹