对人的函数参数验证
pyow的Python项目详细描述
Function argument validation for humans for Python 3!
亮点
- 来自神奇图书馆的直通端口^{
} 来自Sindre Sorhus - 表达性可链接api
- 通过decorator的pythonic方法
- 大量内置验证
- 支持自定义验证
- 用python3写成,字体暗示
注释
由于这是来自javascript库的直接向上端口,因此并非所有功能都可用。 部分原因是这是一个端口,我还没有赶上,而且python不支持所有的用例 就像javascript一样。
安装
$ pip3 install pyow
用法
frompyowimportpyowdefunicorn(input):pyow(input,pyow.string.min_length(5))# ...unicorn(3)>>>ArgumentError:'Expected argument to be of type `str` but received type `int`unicorn('yo')>>>ArgumentError:Expectedstringtohaveaminimumlengthof`3`,got`yo`
或通过decorator
frompyow.decoratorimportvalidate@validate(pyow.string.min_length(5))defunicorn(input):return1
API
pyow(值,谓词)
测试value
是否与提供的predicate
匹配。如果测试失败,则抛出ArgumentError
。
pyow.是否有效(值,谓词)
如果值与谓词匹配,则返回True
,否则返回False
。
pyow.create(谓词)
创建一个可重用的验证器。
check_password=pyow.create(pyow.string.min_length(6))check_password('foo')>>>ArgumentError:('Expected string to have a minimum length of `6`, got `foo`')
pyow.any(谓词:list[谓词])
返回一个谓词,该谓词验证该值是否与给定谓词中的至少一个匹配。
pyow('foo',pyow.any(pyow.string.max_length(3),pyow.number))
pyow.{type}
以下所有类型都返回一个谓词。每个谓词都有一些额外的运算符,您可以使用它们来测试更细粒度的值。
原语
内置类型
谓词
以下谓词在每种类型上都可用。
nix/isnot
反转以下谓词。
pyow(1,pyow.number.nix.infinite)pyow(1,pyow.number.isnot.infinite)pyow('',pyow.string.isnot.empty);>>>ArgumentError:[NOT]Expectedstringtobeempty,got``
是(fn)
使用自定义验证函数。返回True
如果值与验证匹配,则返回False
如果不匹配。
pyow(1,pyow.number.is_(lambdax:x<10))pyow(1,pyow.number.is_(lambdax:x>10))>>>ArgumentError:Expected`1`topasscustomvalidationfunction
除了返回False
,还可以返回导致失败的自定义错误消息。
defgreater_than(max_number:int,x:int):returnx>max_numberorf'Expected `{x}` to be greater than `{max_number}`'};pyow(5,pyow.number.is_(lambdax:greater_than(10,x)))>>>ArgumentError:Expected`5`tobegreaterthan`10`
维护人员
相关
- @sindresorhus/ow-人类的函数参数验证
许可证
麻省理工学院