Importing variables from a namespace object in Python

安稳与你 提交于 2019-12-02 07:09:41

问题


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?

e.g.

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.

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.


回答1:


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.

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 already stated this in his Zen of Python:

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




回答2:


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.

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:

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


来源:https://stackoverflow.com/questions/14697158/importing-variables-from-a-namespace-object-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!