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

zer*_*kms 5 python command-line-interface python-3.x python-3.6

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

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'
Run Code Online (Sandbox Code Playgroud)

ideone: https: //ideone.com/7P7VxI

我预计bar这两种情况都会被设置。

是预期的吗?但我在文档中看不到它。

如果这是预期的,那么除了使用一些自定义操作之外真的没有其他方法可以实现吗?

UPD:我将其报告为文档错误https://bugs.python.org/issue38843

rys*_*son 3

是的,这是预期的。编辑:但仅适用于 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])
Run Code Online (Sandbox Code Playgroud)

添加任何不存在的操作默认值

在您的示例中,如果您在默认对象中设置属性,效果将是相同的:

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'
Run Code Online (Sandbox Code Playgroud)

  • 我报告了一个文档错误 https://bugs.python.org/issue38843 (2认同)