Python argparse parse_args 进入全局命名空间(或者这是一个坏主意的原因) [英] Python argparse parse_args into global namespace (or a reason this is a bad idea)

查看:28
本文介绍了Python argparse parse_args 进入全局命名空间(或者这是一个坏主意的原因)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我主要使用 argparse 在 python 中制作命令行脚本,我通常使用的习惯用法是将参数分配为对象的属性,然后将它们单独解析为与其属性名称匹配的变量.这似乎有点重复.有没有办法将它们全部分配到全局命名空间中并省去分配步骤;或者当某些 Python 行为对我来说似乎违反直觉时经常出现的情况,一些聪明的 Python 专家能否指出我不应该这样做或想要这样做的充分理由?

I've mostly used argparse for making command-line scripts in python, and the idiom I generally use is that I assign the arguments as attributes of an object, then parse them individually to a variable that matches their attribute name. This seems a little repetitive. Is there a way to assign them all into the global namespace and cut out the assignment step; or as is often the case when some python behavior seems counter-intuitive to me, can some wise, python expert point out that there a good reason I should not do this or want to do this?

我现在拥有的是:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--db",type=str, dest='db', nargs='?', default="test")
    parser.add_argument("--collection",type=str, dest='collection', nargs='?', help="Collection, default is test", default="test")
    args = parser.parse_args()
    db = args.db                   # gross! 
    collection = args.collection   # yuck!
    print(db)
    print(collection)

我想要的是:

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--db",type=str, dest='db', nargs='?', default="test")
    parser.add_argument("--collection",type=str, dest='collection', nargs='?', help="Collection, default is test", default="test")
    parser.SUPER_parse_args() # now, db and collection are already in the namespace!
    print(db)
    print(collection)

当我只有 2 个参数时,这看起来并不多,但是如果我有 10 个左右,则将分配步骤加倍,在那里我将 args 对象中已经存在的属性重命名为全局命名空间,开始出错我.

It doesn't seem like much when I only have 2 arguments, but if I have 10 or so, doubling the assign steps, where I rename into the global namespace the attributes that already exist in the args object, starts to bug me.

推荐答案

可以使用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!

我会回应@Martijn 在他的评论中所说的话:

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

不要.只是不要.我会直接使用 args 代替.

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.

这篇关于Python argparse parse_args 进入全局命名空间(或者这是一个坏主意的原因)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆