我注意到在使用自定义命名空间对象时没有设置默认参数值:
import argparse
class CliArgs(object):
foo: str = 'not touched'
parser = argparse.ArgumentParser()
parser.add_argument('--foo', default='bar')
args = CliArgs()
parser.parse_args(namespace=args)
print(args.foo) # 'not touched'
print(parser.parse_args()) # 'bar'
ideone: https://ideone.com/7P7VxI
我希望在这两种情况下都设置 bar
。
这是预期的吗?我在 the documentation 中看不到它虽然。
如果它是预期的,那么除了使用一些自定义操作之外真的没有办法实现它吗?
UPD:我将其报告为文档错误 https://bugs.python.org/issue38843
最佳答案
是的,这是预期的。 编辑:但仅适用于 argparse 开发人员。
参见argparse.py
def parse_known_args(...):
# add any action defaults that aren't present
for action in self._actions:
if action.dest is not SUPPRESS:
if not hasattr(namespace, action.dest):
if action.default is not SUPPRESS:
setattr(namespace, action.dest, action.default)
# add any parser defaults that aren't present
for dest in self._defaults:
if not hasattr(namespace, dest):
setattr(namespace, dest, self._defaults[dest])
add any action defaults that aren't present
在您的示例中,如果您在默认对象中设置属性,效果将是相同的:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', default='bar')
args = argparse.Namespace()
args.foo = 'not touched'
parser.parse_args(namespace=args)
print(args.foo) # 'not touched'
关于python - 当自定义命名空间为对象时,未设置默认 argparse 参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58925420/