从Python中的命名空间对象导入变量 [英] Importing variables from a namespace object in Python

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

问题描述

假设我有一个命名空间args,该命名空间是通过调用parser.parse_args()解析命令行参数而获得的.

Say I have a namespace args that I obtain from calling parser.parse_args(), which parses the command line arguments.

如何将所有变量从该命名空间导入到当前的命名空间?

How can I import all variables from this namespace to my current namespace?

例如

parser.add_argument('-p', '--some_parameter', default=1)

args = parser.parse_args()

# ... code to load all variables defined in the namespace args ...

print some_parameter

我当然可以:

some_parameter = args.some_parameter

但是如果我有大量参数,则每个参数都需要一行这样的行.

but if I have a large number of parameters I would need one such line for each parameter.

是否存在另一种从名称空间导入变量而不必一个接一个地通过变量的方法?

Is there another way of importing variables from a namespace without having to go through them one by one?

PS :from args import *不起作用.

PS2 :我知道这是一个不好的做法,但这在某些极端情况下可能会有所帮助,例如我们在快速原型验证代码并非常快速地进行测试时.

PS2: I am aware that this is a bad practice, but this can help in some corner cases, such us when prototyping code and tests very quickly.

推荐答案

使用这通常不是一个好主意;将这些属性留在名称空间中.

This is generally not that great an idea; leave those attributes in the namespace instead.

与使用这种方法解决的问题相比,您可能会制造出更多的问题,尤其是如果您意外地使用 dest名称遮盖了您关心的内置或本地名称,例如listprint之类的东西.尽情寻找那个错误!

You could create more problems than you solved with this approach, especially if you accidentally configure arguments with a dest name that shadows a built-in or local you care about, such as list or print or something. Have fun hunting down that bug!

蒂姆·彼得斯(Tim Peters)已经在他的《 Python的禅宗》中指出了这一点:

Tim Peters already stated this in his Zen of Python:

命名空间是一个很棒的主意-让我们做更多的事吧!

Namespaces are one honking great idea -- let's do more of those!

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

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