Python的代数类型(特别是提供Sum类型,即Tagged Unions)
项目描述
sumtypes
sumtypes为Python提供代数数据类型。主要好处是实现Sum类型(即Tagged Unions),Python没有本地的表示。产品类型只是具有多个属性的简单对象。
文档在https://sumtypes.readthedocs.org/
此模块使用attrs库提供功能,如属性验证和默认值。
示例
使用装饰器使类成为Sum类型
import attr
from sumtypes import sumtype, constructor, match
@sumtype
class MyType(object):
# constructors specify names for their arguments
MyConstructor = constructor('x')
AnotherConstructor = constructor('x', 'y')
# You can also make use of any feature of the attrs
# package by using attr.ib in constructors
ThirdConstructor = constructor(
one=attr.ib(default=42),
two=attr.ib(validator=attr.validators.instance_of(int)))
然后通过调用构造函数来构造它们
v = MyType.MyConstructor(1)
v2 = MyType.AnotherConstructor('foo', 2)
您可以从标记对象中获取值
assert v.x == 1
assert v2.x == 'foo'
assert v2.y == 2
您检查使用的构造函数
assert type(v) is MyType.MyConstructor
并且,像Scala的case类一样,构造函数类型是主类型的子类
assert isinstance(v, MyType)
并且标记对象支持相等性
assert v == MyType.MyConstructor(1)
assert v != MyType.MyConstructor(2)
也支持简单的模式匹配。要编写覆盖Sum类型所有情况的函数
@match(MyType)
class get_number(object):
def MyConstructor(x): return x
def AnotherConstructor(x, y): return y
def ThirdConstructor(one, two): return one + two
assert get_number(v) == 1
assert get_number(v2) == 2
match确保处理所有情况。如果您真的想写一个‘部分函数’(即不涵盖所有情况的函数),请使用match_partial。
另请参阅
在过去的几年中,帮助Python进行函数式编程的库生态系统已经爆炸式增长。以下是我推荐的一些库
effect - 用于隔离副作用库
pyrsistent - Python中的持久(优化不可变)数据结构
toolz - 一个通用的纯函数库
fn.py - 一组受Scala启发的工具,包括奇特的lambda语法、选项类型和单子
项目详情
下载文件
下载适用于您的平台的文件。如果您不确定选择哪个,请了解有关安装包的更多信息。
源分布
sumtypes-0.1a6.tar.gz (5.3 kB 查看哈希值)
构建分布
sumtypes-0.1a6-py2.py3-none-any.whl (5.8 kB 查看哈希值)
关闭
sumtypes-0.1a6.tar.gz的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 1a6ff095e06a1885f340ddab803e0f38e3f9bed81f9090164ca9682e04e96b43 |
|
MD5 | 53c957667474439914782b6e4a0170cc |
|
BLAKE2b-256 | 3aaa1aa52ae948166291cf615687a733151d4567645beac7e51b7bae3fd88ad4 |
关闭
sumtypes-0.1a6-py2.py3-none-any.whl的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 3e9d71322dd927d25d935072f8be7daec655ea292fd392359a5bb2c1e53dfdc3 |
|
MD5 | 7e30184c8e3bfc02415756891a204a7c |
|
BLAKE2b-256 | 5a294ef1ff91dad16f8396bab999a09011d4939951f47b9729b3f73cc1f74756 |