简体   繁体   English

在Python中从命名空间对象导入变量

[英]Importing variables from a namespace object in Python

Say I have a namespace args that I obtain from calling parser.parse_args() , which parses the command line arguments. 假设我有一个名称空间args ,我从调用parser.parse_args()获得,它解析命令行参数。

How can I import all variables from this namespace to my current namespace? 如何将此命名空间中的所有变量导入到当前命名空间?

eg 例如

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

I could certainly do: 我当然可以这样做:

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 * does not work. PSfrom args import *不起作用。

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. PS2 :我知道这是一个不好的做法,但这在一些极端情况下会有所帮助,例如我们在非常快速地对代码进行原型设计和测试时。

Update your local namespace with the result of the vars() function : 使用vars()函数的结果更新本地命名空间:

globals().update(vars(args))

This is generally not that great an idea; 这通常不是一个好主意; leave those attributes in the namespace instead. 将这些属性保留在命名空间中。

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. 您可以创建比使用此方法解决的问题更多的问题,特别是如果您不小心配置了具有影响您关注的内置或本地的dest名称的参数,例如listprint或其他内容。 Have fun hunting down that bug! 玩得开心追捕那个虫子!

Tim Peters already stated this in his Zen of Python: 蒂姆彼得斯已经在他的禅宗Python中说明了这一点:

Namespaces are one honking great idea -- let's do more of those! 命名空间是一个很棒的主意 - 让我们做更多的事情吧!

Probably the worst idea ever: since you can pass an arbitrary object to parse_args() , pass the __builtins__ module, so that all attributes can be looked up as local variables. 可能是有史以来最糟糕的想法:因为您可以将任意对象传递给parse_args() ,传递__builtins__模块,以便可以将所有属性都查找为局部变量。

p = argparse.ArgumentParser()
p.add_argument("--foo")
p.parse_args( "--foo bar".split(), __builtins__)
print foo

This will even "work" for parameters whose destinations aren't valid Python identifiers: 对于目标不是有效Python标识符的参数,这甚至可以“工作”:

# To use the example given by Francis Avila in his comment on Martijn Pieters' answer
getattr(__builtins__, '2my-param')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM