【问题标题】:How can I merge two argparse Namespaces in Python 2.x?如何在 Python 2.x 中合并两个 argparse 命名空间?
【发布时间】:2019-10-01 20:13:28
【问题描述】:

我想在 Python 2.x 中合并 2 个 argparse.Namespace 对象。

在 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

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

【问题讨论】:

  • 这对您有用吗? stackoverflow.com/questions/38050873/… 这对我来说不是超级有用。
  • 我可以有点愤世嫉俗,只是说......我们可以完全停止使用python 2吗? :P(感谢 python 3 中的解决方案!)

标签: python-2.x


【解决方案1】:

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

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 3 中的 arg 冲突。由于双星 ** 语法在 Python 2 中不起作用,这在问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-29
  • 2014-07-02
  • 2020-06-18
  • 2021-01-03
  • 2011-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多