Python argparse parse_args into global namespace (or a reason this is a bad idea)

一曲冷凌霜 提交于 2019-12-05 02:22:14

You can do this using globals:

globals().update(args.__dict__)

however, you really *shouldn't do that. From the zen of python,

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

I'll echo what @Martijn said in his comment:

Don't. Just don't. I'd use args directly instead.

Keep things as nicely separated as you can. It makes for more maintainable and easier to understand code.

This is what I did. It helps with variable collision but not maintainability.

parser_args = parser.parse_args()
if parser_args.verbose:
    globals().update(argparse.Namespace(verbose=parser_args.verbose).__dict__)
Joe

To add onto mgilson's answer:

Consider using locals().update(args.__dict__) instead; this will update the current namespace rather than the global namespace.

You can also do this using locals() or vars(). See this Stack Overflow post for a nice explanation on the difference between the two.

I'm a bit late for Mittonchops, but hopefully this helps others.

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