Python:从命名空间中提取变量 [英] Python: Extract variables out of namespace

查看:34
本文介绍了Python:从命名空间中提取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 中使用 argparse 来解析命令行参数:

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()

现在我想用 abc 做一些计算.然而,我觉得一直写 args.a + args.b + args.c 很烦人.

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]

这样我就可以写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))

如果您在一个函数中并希望它们作为该函数的局部变量,您可以在 Python 2.x 中按如下方式执行此操作:

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.

此技巧在 Python 3 中不起作用,其中 exec 不是语句,在其他 Python 变体(例如 Jython 或 IronPython)中也不可能.

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.

不过,总的来说,我建议为 args 对象使用较短的名称,或者使用剪贴板.:-)

Overall, though, I would recommend just using a shorter name for the args object, or use your clipboard. :-)

这篇关于Python:从命名空间中提取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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