gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 11:46:03 25 4
gpt4 key购买 nike

我要合并 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com