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

查看:125
本文介绍了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__)

但是,您确实* 不应该这样做.从禅宗的python开始,

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.

将所有内容尽可能地分开.它使代码更易于维护和理解.

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天全站免登陆