Importing Variables From A Namespace Object In Python
Solution 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!
Solution 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' answergetattr(__builtins__, '2my-param')
Post a Comment for "Importing Variables From A Namespace Object In Python"