如何创建 Python 命名空间(argparse.parse_args 值)? [英] How do I create a Python namespace (argparse.parse_args value)?

查看:32
本文介绍了如何创建 Python 命名空间(argparse.parse_args 值)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了交互式测试我的 python 脚本,我想创建一个 Namespace 对象,类似于 argparse.parse_args() 返回的对象.显而易见的方式,

<预><代码>>>>导入参数解析>>>解析器 = argparse.ArgumentParser()>>>parser.parse_args()命名空间()>>>parser.parse_args("-a")用法:[-h]:错误:无法识别的参数:-a进程 Python 异常退出,代码 2

可能会导致 Python repl 因愚蠢的错误而退出(如上所述).

那么,创建具有给定属性集的 Python 命名空间的最简单方法是什么?

例如,我可以即时创建一个 dict (dict([("a",1),("b","c")])) 但我不能将它用作 Namespace:

AttributeError: 'dict' 对象没有属性 'a'

解决方案

您可以创建一个简单的类:

 类命名空间:def __init__(self, **kwargs):self.__dict__.update(kwargs)

它的工作方式与 argparse Namespace 类在属性方面完全相同:

<预><代码>>>>args = 命名空间(a=1, b='c')>>>args.a1>>>参数文件'C'

或者,只需导入类;它可以从 argparse 模块获得:

from argparse import Namespaceargs = 命名空间(a=1, b='c')

从 Python 3.3 开始,还有 types.SimpleNamespace,基本上做同样的事情:

<预><代码>>>>从类型导入 SimpleNamespace>>>args = SimpleNamespace(a=1, b='c')>>>args.a1>>>参数文件'C'

这两种类型是不同的;SimpleNamespace 主要用于sys.implementation 属性和time.get_clock_info() 的返回值.

进一步比较:

  • 两个类都支持相等性测试;对于同一个类的两个实例,instance_a == instance_b 如果它们具有相同的属性和相同的值,则为真.
  • 两个类都有一个有用的 __repr__ 来显示它们具有哪些属性.
  • Namespace() 对象支持包含测试;'attrname' in instance 如果命名空间实例具有属性 namend attrname,则为真.SimpleNamespace 没有.
  • Namespace() 对象有一个未记录的 ._get_kwargs() 方法,该方法返回一个 (name, value) 属性的排序列表实例.您可以使用 sorted(vars(instance).items()) 为任一类获得相同的结果.
  • 虽然 SimpleNamespace() 是用 C 实现的,而 Namespace() 是用 Python 实现的,但属性访问并没有更快,因为两者都使用相同的 __dict__存储属性.对于 SimpleNamespace() 实例,相等性测试和生成表示的速度要快一些.

To interactively test my python script, I would like to create a Namespace object, similar to what would be returned by argparse.parse_args(). The obvious way,

>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.parse_args()
Namespace()
>>> parser.parse_args("-a")
usage: [-h]
: error: unrecognized arguments: - a

Process Python exited abnormally with code 2

may result in Python repl exiting (as above) on a silly error.

So, what is the easiest way to create a Python namespace with a given set of attributes?

E.g., I can create a dict on the fly (dict([("a",1),("b","c")])) but I cannot use it as a Namespace:

AttributeError: 'dict' object has no attribute 'a'

解决方案

You can create a simple class:

class Namespace:
    def __init__(self, **kwargs):
        self.__dict__.update(kwargs)

and it'll work the exact same way as the argparse Namespace class when it comes to attributes:

>>> args = Namespace(a=1, b='c')
>>> args.a
1
>>> args.b
'c'

Alternatively, just import the class; it is available from the argparse module:

from argparse import Namespace

args = Namespace(a=1, b='c')

As of Python 3.3, there is also types.SimpleNamespace, which essentially does the same thing:

>>> from types import SimpleNamespace
>>> args = SimpleNamespace(a=1, b='c')
>>> args.a
1
>>> args.b
'c'

The two types are distinct; SimpleNamespace is primarily used for the sys.implementation attribute and the return value of time.get_clock_info().

Further comparisons:

  • Both classes support equality testing; for two instances of the same class, instance_a == instance_b is true if they have the same attributes with the same values.
  • Both classes have a helpful __repr__ to show what attributes they have.
  • Namespace() objects support containment testing; 'attrname' in instance is true if the namespace instance has an attribute namend attrname. SimpleNamespace does not.
  • Namespace() objects have an undocumented ._get_kwargs() method that returns a sorted list of (name, value) attributes for that instance. You can get the same for either class using sorted(vars(instance).items()).
  • While SimpleNamespace() is implemented in C and Namespace() is implemented in Python, attribute access is no faster because both use the same __dict__ storage for the attributes. Equality testing and producing the representation are a little faster for SimpleNamespace() instances.

这篇关于如何创建 Python 命名空间(argparse.parse_args 值)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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