当自定义命名空间为对象时,未设置默认 argparse 参数值

Default argparse argument value is not set when a custom namespace is object

我注意到在使用自定义命名空间对象时未设置默认参数值:

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 中看不到它。

如果这是预期的,那么除了使用一些 custom 操作之外真的没有办法实现它吗?

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'