为什么 Python 的 argparse 模块动态地(隐式地)创建变量名而不是强制显式赋值?

Why does Python's argparse module dynamically (and implicitly) create the variable name instead of forcing explicit assignment?

基本上,对于 argparse,我会做:

parser = argparse.ArgumentParser(description="This is a command line parser!")
group = parser.add_mutually_exclusive_group()
group.add_argument('--send-emails', action="store_true", help="This will send production emails")
args = parser.parse_args()
if args.send_emails:
  send_emails()

其中 "--send-emails" 自动大小写为 "send_emails"。这好像有点conventiony/implicity。强制使用 name= 参数感觉会更明确。

是否有任何我可以阅读的 PEP 或邮件列表线程来帮助我理解这样做的理由?

编辑:我找到了这个用于 argparse 的 PEP,但快速浏览似乎表明它没有解决这个特定的问题。 https://www.python.org/dev/peps/pep-0389/

理由是只指定一次名称更方便。如果愿意,您可以使用 dest="name" 参数提供明确的名称。但是为什么要说两次呢?

optparse 做同样的事情——从选项字符串中导出默认值 dest

getopt 还将 option stringslong options(即参数标志)与值配对。

所以argparse是在抄袭它的前辈。

argparse 不同之处在于它还解析 positional 参数。对于那些 dest 是第一个(非关键字)参数。

总的来说 argparse 试图为您提供尽可能多的功能,同时使常见情况相对简单,主要是通过使用逻辑默认值。 nargsactiontypedefault 都有默认值。可选关键字参数在 public API.

中很普遍