python - 处理可选函数参数

标签 python

假设您有一个接受一个或多个可选参数的函数。解决这个问题的最佳方法是什么?

这是一个函数,其中有两个强制参数和一个可更改输出的可选参数:

def get_cases(**kwargs):
    """Returns a list of test cases for a test suite or specific section in a test suite."""
    if 'section_id' not in kwargs:
        req = requests.get(settings.URL + 'get_cases/' + str(kwargs['project_id']) +
                           '&suite_id=' + str(kwargs['suite_id']),
                           auth=(settings.USR, settings.PWD), headers=headers)
    else:
        req = requests.get(settings.URL + 'get_cases/' + str(kwargs['project_id']) +
                           '&suite_id=' + str(kwargs['suite_id']) +
                           '&section_id=' + str(kwargs['section_id']),
                           auth=(settings.USR, settings.PWD), headers=headers)
    return req.json()

我使用 **kwargs 来捕获所有值,然后如果字典中存在可选值,则我执行不同的操作。

除了上面代码中的冗余(2个重复行)之外,是否有更好的方法来处理可选参数?目前我对重复的行并不太在意。

最佳答案

只需使用 keyword argument :(如果可以传递 None,则可以将 None 替换为不同的值)。如果section_id可以是*anything,那么将section_id设置为一个特殊的对象而不是None(可以使用object()生成对象)(连续调用 object() 不相等,因为内存地址不同)。

def get_cases(some_args, another_arg, section_id=None):
    if section_id is None:
        # A value for section_id wasn't passed.
    else:
        # An value for section_id was passed.

^ 使用我的解决方案传递特殊对象将使代码认为参数未传递

关于python - 处理可选函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686177/

相关文章:

python - 如何在第三方 python 库中禁用 SSL 验证?

python - 安排具有单调时间的精确时间

python - 为什么在 python 脚本中使用 yt-dlp 时 FFmpeg 不起作用?

python - 将不规则列表的单列数据框分解为多列

python - Pygame.key.get_pressed() 中的关键常量值是什么?

python - NameError:未定义名称“LabelEncoder”

python - 在 Python 中为我的日期添加 1 天

python使用测试分数列表

python - 从基于列的数组返回多数加权投票

Android 应用程序 ABI 和 native 调试