python-2.x - 如何在 Python 2.x 中合并两个 argparse 命名空间?

标签 python-2.x

我要合并 2 argparse.Namespace Python 2.x 中的对象

在 python 3.x 中,我可以做这样的事情:

from argparse import Namespace

# The 2 initial objects
options_foo = Namespace(foo="foo")
options_bar = Namespace(bar="bar")

# the merged object
options_baz = Namespace(**vars(options_foo), **vars(options_bar))

并得到:
print(options_baz)
# Namespace(foo="foo", bar="bar")

但在 python 2.x 中我不能。我收到以下错误。
SyntaxError: invalid syntax

有没有简单的方法来实现这一目标?

最佳答案

这是一个合并两个参数的函数:

def merge_args_safe(args1: Namespace, args2: Namespace) -> Namespace:
    """
    Merges two namespaces but throws an error if there are keys that collide.

    ref: https://stackoverflow.com/questions/56136549/how-can-i-merge-two-argparse-namespaces-in-python-2-x
    :param args1:
    :param args2:
    :return:
    """
    # - the merged args
    # The vars() function returns the __dict__ attribute to values of the given object e.g {field:value}.
    args = Namespace(**vars(args1), **vars(args2))
    return args
测试
def merge_args_test():
    args1 = Namespace(foo="foo", collided_key='from_args1')
    args2 = Namespace(bar="bar", collided_key='from_args2')

    args = merge_args(args1, args2)
    print('-- merged args')
    print(f'{args=}')
输出:
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1483, in _exec
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/Users/brando/ultimate-utils/ultimate-utils-proj-src/uutils/__init__.py", line 1202, in <module>
    merge_args_test()
  File "/Users/brando/ultimate-utils/ultimate-utils-proj-src/uutils/__init__.py", line 1192, in merge_args_test
    args = merge_args(args1, args2)
  File "/Users/brando/ultimate-utils/ultimate-utils-proj-src/uutils/__init__.py", line 1116, in merge_args
    args = Namespace(**vars(args1), **vars(args2))
TypeError: argparse.Namespace() got multiple values for keyword argument 'collided_key'
python-BaseException
你可以在这个库中找到它:https://github.com/brando90/ultimate-utils

如果您想解决冲突,请执行以下操作:
def merge_two_dicts(starting_dict: dict, updater_dict: dict) -> dict:
    """
    Starts from base starting dict and then adds the remaining key values from updater replacing the values from
    the first starting/base dict with the second updater dict.

    For later: how does d = {**d1, **d2} replace collision?

    :param starting_dict:
    :param updater_dict:
    :return:
    """
    new_dict: dict = starting_dict.copy()   # start with keys and values of starting_dict
    new_dict.update(updater_dict)    # modifies starting_dict with keys and values of updater_dict
    return new_dict

def merge_args(args1: Namespace, args2: Namespace) -> Namespace:
    """

    ref: https://stackoverflow.com/questions/56136549/how-can-i-merge-two-argparse-namespaces-in-python-2-x
    :param args1:
    :param args2:
    :return:
    """
    # - the merged args
    # The vars() function returns the __dict__ attribute to values of the given object e.g {field:value}.
    merged_key_values_for_namespace: dict = merge_two_dicts(vars(args1), vars(args2))
    args = Namespace(**merged_key_values_for_namespace)
    return args
测试:
def merge_args_test():
    args1 = Namespace(foo="foo", collided_key='from_args1')
    args2 = Namespace(bar="bar", collided_key='from_args2')

    args = merge_args(args1, args2)
    print('-- merged args')
    print(f'{args=}')
    assert args.collided_key == 'from_args2', 'Error in merge dict, expected the second argument to be the one used' \
                                                 'to resolve collision'

关于python-2.x - 如何在 Python 2.x 中合并两个 argparse 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56136549/

相关文章:

python - 是否有可能使用 python 2 和 python 3 模块的应用程序?

Python自定义集交集

python - 从列表指向字典变量

Python、__getitem__、切片和负索引

python - 调用 type(1/2) 返回整数?

python - 在 Python 2.x 中转换 u'\xe 0' to '\u00E0'?

python - 列表推导式中定义的变量是否会泄漏到封闭范围中?

python - 空字符串而不是不匹配的组错误

python - 如何检查用户是否将 'input' 或 'raw_input' 提示留空?

python:打印短utf编码字符串时遇到问题