使用 argparse 参数作为关键字参数 [英] Using argparse arguments as keyword arguments

查看:36
本文介绍了使用 argparse 参数作为关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在使用 argparse 解析我的命令行后,我有一个 args 命名空间.现在,我想用它来创建一些像这样的对象:

foo = Foo(bar=args.bar)

不幸的是,我的限制是如果一个关键字参数被设置,它不能是None.现在,我需要检查 args.bar 是否已设置并采取相应措施:

如果 args.bar:foo = Foo(bar=args.bar)别的:foo = foo()

这很笨拙,并且无法扩展以适应更多参数.我想要的是这样的:

foo = Foo(**args.__dict__)

但这仍然受到我最初的问题的影响,并且对于不是 __init__ 方法的关键字参数的键也不起作用.有什么好的方法可以实现这些目标吗?

解决方案

你可以试试这样的:

<预><代码>>>>defined_args = {k:v for k,v in args._get_kwargs() 如果 v 不是 None}>>>foo = Foo(**defined_args)

例如:

<预><代码>>>>导入参数解析>>>args = argparse.Namespace(key1=None,key2='value')>>>{k:v for k,v in args._get_kwargs() 如果 v 不是 None}{'key2':'值'}

但是请注意,_get_kwargs() 不是公共 API 的一部分,因此可能会或可能不会在未来的版本/版本中提供.

Let's say I have an args namespace after parsing my command line with argparse. Now, I want to use this to create some objects like this:

foo = Foo(bar=args.bar)

Unfortunately, I have the restriction that if a keyword argument is set, it must not be None. Now, I need to check if args.bar is set and act accordingly:

if args.bar:
    foo = Foo(bar=args.bar)
else:
    foo = Foo()

This is unwieldy and doesn't scale for more arguments. What I'd like to have, is something like this:

foo = Foo(**args.__dict__)

but this still suffers from my initial problem and additionally doesn't work for keys that are not keyword arguments of the __init__ method. Is there a good way to achieve these things?

解决方案

You could try something like this:

>>> defined_args = {k:v for k,v in args._get_kwargs() if v is not None}
>>> foo = Foo(**defined_args)

For example:

>>> import argparse
>>> args = argparse.Namespace(key1=None,key2='value')
>>> {k:v for k,v in args._get_kwargs() if v is not None}
{'key2': 'value'}

Note, however, that _get_kwargs() is not part of the public API so may or may not be available in future releases/versions.

这篇关于使用 argparse 参数作为关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆