从 Python 中的命名空间对象导入变量 [英] Importing variables from a namespace object in 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.
推荐答案
使用 vars()
函数:
Update your local namespace with the result of the vars()
function:
globals().update(vars(args))
这通常不是一个好主意;将这些属性保留在命名空间中.
This is generally not that great an idea; leave those attributes in the namespace instead.
您可能会产生比使用这种方法解决的问题更多的问题,特别是如果您不小心使用 dest
name 隐藏你关心的内置或本地,例如 list
或 print
或其他东西.寻找那个错误,玩得开心!
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 Zen 中已经说明了这一点:
Tim Peters already stated this in his Zen of Python:
命名空间是一个很棒的想法——让我们做更多这样的事情!
Namespaces are one honking great idea -- let's do more of those!
这篇关于从 Python 中的命名空间对象导入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!