python - 如何在 Python 中选择性地传递带有非默认值的参数?

标签 python syntactic-sugar

我有以下方法:

def a(b='default_b', c='default_c', d='default_d'):
    # …
    pass

我有一些命令行界面,允许提供变量 user_buser_cuser_d 或将它们设置为 - 即简单的Python argparse 模块。

我想调用如下电话:

a(b=user_b if user_b is not None,
  c=user_c if user_c is not None,
  d=user_d if user_d is not None)

如果变量是None,我想使用方法参数中的默认值。

我发现的唯一方法是检查用户变量的所有组合:

if not user_b and not user_c and not user_d:
    a()
elif not user_b and not user_c and user_d:
    a(d)
…
elif user_b and user_c and user_d:
    a(b, c, d)

什么是更高效、更奇特、更Python式的方法来解决我的问题?

最佳答案

arg_dict = {}
if user_b is not None:
    arg_dict["b"] = user_b
if user_c is not None:
    arg_dict["c"] = user_c
if user_d is not None:
    arg_dict["d"] = user_d

a(**arg_dict)

虽然不太漂亮。

更好的方法是重写函数 a 以接受 None 作为默认答案,然后检查它。 (即如果 b 为 None:b = "default_b")

关于python - 如何在 Python 中选择性地传递带有非默认值的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39877826/

相关文章:

layout - Haskell 记录语法

javascript - <boolean expression> && statement() 是否与 if(<boolean expression>) statement() 相同?

python - numpy 特征值正确但特征向量错误

python - 如何用多个字符替换合并两个字符串列表

python - Python中默认参数的规则是什么?

ruby-on-rails - build_ 是语法糖吗?

perl - 有没有更干净的方法可以有条件地将 'last' 排除在这个 Perl 循环之外?

python - 如何计算两个 NumPy 数组中不匹配元素的总和

python - 无法在 MAC OS 中通过 pip 安装 rpy2

python - 在 python 中通过引用或值处理数据