[英]Python: Extract variables out of namespace
I'm using argparse in python to parse commandline arguments: 我在python中使用argparse来解析命令行参数:
parser = ArgumentParser()
parser.add_argument("--a")
parser.add_argument("--b")
parser.add_argument("--c")
args = parser.parse_args()
Now I want to do some calculations with a
, b
, and c
. 现在我想用a
, b
和c
做一些计算。 However, I find it tiresome to write args.a + args.b + args.c
all the time. 但是,我觉得编写args.a + args.b + args.c
一直很烦人。
Therefore, I'm extracting those variables: 因此,我正在提取这些变量:
a, b, c = [args.a, args.b, args.c]
Such that I can write a + b + c
. 这样我就可以写a + b + c
。
Is there a more elegant way of doing that? 有更优雅的方式吗?
Manual extraction gets very tedious and error prone when adding many arguments. 添加许多参数时,手动提取变得非常繁琐且容易出错。
If you want them as globals, you can do: 如果你想要它们作为全局变量,你可以这样做:
globals().update(vars(args))
If you're in a function and want them as local variables of that function, you can do this in Python 2.x as follows: 如果您在函数中并希望它们作为该函数的局部变量,则可以在Python 2.x中执行此操作,如下所示:
def foo(args):
locals().update(vars(args))
print a, b, c
return
exec "" # forces Python to use a dict for all local vars
# does not need to ever be executed! but assigning
# to locals() won't work otherwise.
This trick doesn't work in Python 3, where exec
is not a statement, nor likely in other Python variants such as Jython or IronPython. 这个技巧在Python 3中不起作用,其中exec
不是语句,也不可能在其他Python变体中,如Jython或IronPython。
Overall, though, I would recommend just using a shorter name for the args
object, or use your clipboard. 但总的来说,我建议只使用args
对象的较短名称,或使用剪贴板。 :-) :-)
You can add things to the local scope by calling locals()
. 您可以通过调用locals()
将内容添加到本地范围。 It returns a dictionary that represents the currently available scope. 它返回一个表示当前可用范围的字典。 You can assign values to it as well - locals()['a'] = 12
will result in a
being in the local scope with a value of 12. 可以将值分配给它,以及- locals()['a'] = 12
将导致a
在局部范围内具有12的值存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.