具有正常默认值的不可变结构
istruct的Python项目详细描述
在collections.namedtuple之上构建的具有正常默认值的不可变结构
目标
- 不可变的、类似字典的数据结构(注:^ {Tt2} $是{{EM1} $ < EEM > Python中现有的{TT3}$ $的不可变版本)
- 最小值
- 支持必需的和可选字段(带默认值)
- 严格禁止位置参数
安装
pip install istruct
快速启动
首先,创建一个名为person的istruct对象,其中first_name和last_name是必需的,而middle_name、dob和email是可选的(指定了默认值)。
>>> from istruct import istruct >>> person = istruct("first_name", "last_name", middle_name="", dob="2000-01-01", email=None)
然后,使用first_name、last_name和middle_name创建person的实例。
>>> p = person(first_name="Jim", last_name="Raynor", middle_name="Eugene") >>> p istruct(first_name='Jim', last_name='Raynor', email=None, dob='2000-01-01', middle_name='Eugene')
您可以像通常那样检索字段值。
>>> p.first_name 'Jim' >>> p.dob '2000-01-01'
p是不可变的,这意味着在创建后不能对其进行修改。因此,下面这样的set/delete操作将失败,引发一个AttributeError。
>>> p.first_name = "James" Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't set attribute >>> del p.email Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: can't delete attribute
istruct只接受命名/关键字参数。它严格禁止按设计使用位置参数。
>>> p = person("Jim", "Raynor") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/microamp/src/microamp/istruct/istruct/__init__.py", line 52, in _istruct "(%d found)" % (len(positional),)) TypeError: No positional arguments are allowed in istruct (2 found)
istruct将在省略一个或多个必需的字段时引发TypeError。
>>> p = person(last_name="Raynor") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/microamp/src/microamp/istruct/istruct/__init__.py", line 56, in _istruct return nt(**merge_dicts(kwargs, attrs)) TypeError: __new__() missing 1 required positional argument: 'first_name'
测试版本
- python 2.7版
- python 3.2
- Python3.3
- Python3.4
- Python3.5
- python 3.6
- 皮比
- PYPY3
待办事项
- 找到注释类型的方法
许可证
麻省理工学院