Python:从名称空间中提取变量 [英] Python: Extract variables out of namespace
问题描述
我正在python中使用argparse来解析命令行参数:
parser = ArgumentParser()
parser.add_argument("--a")
parser.add_argument("--b")
parser.add_argument("--c")
args = parser.parse_args()
现在,我想对a
,b
和c
进行一些计算.但是,我发现一直不停地写args.a + args.b + args.c
很麻烦.
因此,我正在提取这些变量:
a, b, c = [args.a, args.b, args.c]
我可以写a + b + c
.
有没有更优雅的方法呢?
添加许多参数时,手动提取变得非常繁琐且容易出错.
如果希望将它们用作全局变量,则可以执行以下操作:
globals().update(vars(args))
如果您使用的是函数,并且希望将它们作为该函数的局部变量,则可以在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.
此技巧在Python 3中不起作用,在Python 3中,exec
不是语句,在其他Python变体(如Jython或IronPython)中也不可能.
总的来说,我建议对args
对象使用较短的名称,或者使用剪贴板. :-)
I'm using argparse in python to parse commandline arguments:
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
. However, I find it tiresome to write args.a + args.b + args.c
all the time.
Therefore, I'm extracting those variables:
a, b, c = [args.a, args.b, args.c]
Such that I can write 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:
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.
Overall, though, I would recommend just using a shorter name for the args
object, or use your clipboard. :-)
这篇关于Python:从名称空间中提取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!