checktypes软件包

用于创建实用程序类的库,为类型提供了良好的抽象

检查和数据验证。

基本示例

创建

面向对象的api

在要继承的CheckType旁边选择一个基类并定义一个predicate()staticmethod或classmethod>>>fromchecktypesimportCheckType>>>classPositiveInteger(int,CheckType):..."'int' > 0"...@staticmethod...defpredicate(n):...returnn>0...>>>classHumanAge(int,CheckType):..."'int' between 0 and 125"...minval=0...maxval=125...@classmethod...defpredicate(cls,val):...returncls.minval<=val<=cls.maxval...

或者,也可以使用lambdas来定义较短的类。>>>classPositiveInteger(int,CheckType):..."'int' > 0"...predicate=lambdan:n>0...>>>classHumanAge(int,CheckType):..."'int' between 0 and 125"...minval=0...maxval=125...predicate=classmethod(lambdacls,n:cls.minval<=n<=cls.maxval)...

功能api

另一种方法是使用checktype()工厂。>>>fromchecktypesimportchecktype>>>PositiveInteger=checktype('PositiveInteger',int,lambdan:n>0,"'int' > 0")>>>HumanAge=checktype(...'HumanAge',int,doc="'int' between 0 and 125",minval=0,maxval=125,...predicate=classmethod(lambdacls,n:cls.minval<=n

用法

isinstance()超载>>>isinstance(1,PositiveInteger)True>>>isinstance(-1,PositiveInteger)False>>>isinstance('a',PositiveInteger)False

validate()类方法>>>PositiveInteger.validate(1)# No output => the value is a valid one>>>PositiveInteger.validate(-1)Traceback(mostrecentcalllast):...ValueError:expected'PositiveInteger'('int'>0)butgot-1>>>PositiveInteger.validate('a')Traceback(mostrecentcalllast):...TypeError:expected'PositiveInteger'('int'>0)butgot'str'

register()类方法>>>isinstance(0,PositiveInteger)False>>>PositiveInteger.validate(0)Traceback(mostrecentcalllast):...ValueError:expected'PositiveInteger'('int'>0)butgot0>>>PositiveInteger.register(0)# Now let pass 0>>>isinstance(0,PositiveInteger)True>>>PositiveInteger.validate(0)

as_descriptor()类方法>>>classCircle:...radius=PositiveInteger.as_descriptor()...>>>c=Circle()>>>c.radius=1>>>c.radius=-1Traceback(mostrecentcalllast):...ValueError:expected'PositiveInteger'('int'>0)butgot-1for'radius'attributeof'Circle'object>>>c.radius='a'Traceback(mostrecentcalllast):...TypeError:expected'PositiveInteger'('int'>0)butgot'str'for'radius'attributeof'Circle'object

checktyped带有类型提示(3.6+样式)的decorator>>>fromchecktypesimportchecktyped>>>@checktyped...classPoint2D:...x:float...y:float...>>>p=Point2D()>>>p.x=0.0>>>p.y=1.0>>>p.x='a'Traceback(mostrecentcalllast):...TypeError:expected'float'butgot'str'for'x'attributeof'Point2D'object

实例化

根据概念CheckTypes最初并不打算被实例化。但既然这是一项普通的任务

为了将一个值转换成另一个类型,添加了支持以使构造函数返回一个值

与python中的标准类具有相同的规则,但有三项除外:

1-返回的值永远不是类的实例,而是一个类的实例。>>>PositiveInteger(1)1>>>n=PositiveInteger(1)>>>print(n,type(n),sep=': ')1:

2-如果该值不满足isinstance()检查,则会提高ValueError。>>>PositiveInteger(-1)Traceback(mostrecentcalllast):...ValueError:-1cannotbeinterpretedasa'PositiveInteger'('int'>0)

3-__init__()和__new__()被忽略。>>>classMyInt(int,CheckType):...def__new__(cls,x):...return'unexpected thing'...def__init__(self,x):...self.my_attr='some value'...>>>x=MyInt(1)>>>x1>>>x.my_attrTraceback(mostrecentcalllast):...AttributeError:'int'objecthasnoattribute'my_attr'

仍然可以提供两个类属性来添加对更好实例化的支持:

1-default

如果不带参数调用类,则它提供要返回的值。

它的优点之一是:它解决了默认值不合适的问题。>>>classNegativeInteger(int,CheckType):...default=-1...predicate=lambdan:n<0...>>>NegativeInteger()-1>>>delNegativeInteger.default>>>NegativeInteger()# int() -> 0Traceback(mostrecentcalllast):...ValueError:0cannotbeinterpretedasa'NegativeInteger'

2-factory()

它是一个可调用的,负责返回新对象。

从ABC继承时特别有用。>>>fromcollections.abcimportSized>>>classThreePlace(Sized,CheckType):...factory=tuple...predicate=lambdas:len(s)==3...>>>ThreePlace(range(1,4))(1,2,3)>>>ThreePlace([4,5,6])(4,5,6)>>>ThreePlace('789')('7','8','9')

请注意,返回值仍将被检查。>>>defbadfactory(*args,**kwarg):...return'bad value'...>>>ThreePlace.factory=badfactory>>>ThreePlace((1,2,3))Traceback(mostrecentcalllast):...ValueError:'bad value'cannotbeinterpretedasa'ThreePlace'>>>delThreePlace.factory>>>ThreePlace.default=0>>>ThreePlace()Traceback(mostrecentcalllast):...TypeError:'int'objectcannotbeinterpretedasa'ThreePlace'

有关其他示例,请参见Recipes.md。

欢迎加入QQ群-->: 979659372

推荐PyPI第三方库

python类型提示模块包_Python checktypes包_程序模块 - PyPI - Python中文网相关推荐

  1. python cmd下载模块_Python cmd包_程序模块 - PyPI - Python中文网

    CMDY 从python运行命令的一个方便的包 安装# latest version pip install git+https://github.com/pwwang/cmdy # released ...

  2. python orange3_Python Orange3包_程序模块 - PyPI - Python中文网

    [橙色]是一个基于组件的数据挖掘软件.它包括一系列数据 可视化.探索.预处理和建模技术.可能是 通过漂亮直观的用户界面使用,或者对于更高级的用户, 作为python编程语言的模块. 这是最新版本的or ...

  3. python安装dill_Python dill包_程序模块 - PyPI - Python中文网

    关于dill dill扩展python的pickle模块以进行序列化和反序列化 python对象的大多数内置python类型.串行化 是将对象转换为字节流的过程,反之亦然 其中之一是将字节流转换回py ...

  4. python类型提示模块包_(任何)python模块的类型提示是什么?

    and types.ModuleType() is a constructor. 那没关系. types.ModuleType仍然是对类型的引用,就像str和int一样.不需要通用的Module [t ...

  5. python cv模块_Python cv包_程序模块 - PyPI - Python中文网

    Cv 检查python模块的版本. 查询pypi并在所有可用版本中查找.__version__. 如果版本已经存在,则会引发错误. 在ci中很有用,可以记住更改库版本. 有关python模块版本控制的 ...

  6. python repusts模块_Python tslearn包_程序模块 - PyPI - Python中文网

    tslearn是一个python包,它为分析时间序列提供机器学习工具. 这个包基于scikit-learn.numpy和scipy库. 依赖关系Cython numpy numba scipy sci ...

  7. python下载matplotlib.finance模块_Python pyfinance包_程序模块 - PyPI - Python中文网

    PyFinance pyfinance是一个python包,用于投资管理和安全回报分析. 它是对面向量化金融的现有软件包的补充,例如pyfolio, 熊猫数据读取器,以及fecon235 支持巨蟒3. ...

  8. python queue模块安装_Python queue包_程序模块 - PyPI - Python中文网

    沃特?另一个消息队列? 考虑到消息队列的激增,人们可能倾向于相信 发明更多不是答案.使用现有的解决方案是 多次尝试与大多数现有的消息队列产品. 其他的失败(对于我们的用例). queuey是用来处理大 ...

  9. python ssh登陆模块_Python sshh包_程序模块 - PyPI - Python中文网

    sshh是一个ssh帮助工具,用于在ssh代理中批量注册ssh私钥. sshh的主要目的是避免在 在ssh代理中注册的密钥数超过一定数量.当 当服务器设置私钥上限时,超过了密钥尝试的上限 严格的尝试. ...

最新文章

  1. AT2362 [AGC012B] Splatter Painting(思维、dfs染色、剪枝)
  2. 送餐机器人被解雇,人工智能“人性”待进化
  3. 成功解决Redirection is not supported
  4. recycleview 嵌套高度问题_RecyclerView嵌套子RecyclerView无法正常显
  5. [WPF系列]Button 自定义
  6. ipad连接电脑_这些应用让iPad生产力分分钟UP
  7. Android listview addHeaderView 和 addFooterView 详解
  8. Python正则表达式re.sub使用
  9. 计算机电源插头有哪几种,盘点电连接器常见的使用类型
  10. listView使用checkBox的实现
  11. 关闭eureka注册中心
  12. 关于在VC + + 2008 VCRedist安装时生成在根目录下的临时文件
  13. Java获取本机ip地址的代码
  14. python发outlook邮件_python对outlook邮件整理
  15. python自学课堂_python自学——列表
  16. Codeforces Round #322 A Vasya the Hipster
  17. Android 4.2官方文档chm格式下载
  18. 搜索技术——遗传算法
  19. AAAI 2021-TextGAIL:Generative Adversarial Imitation Learning for Text Generation
  20. MSSQL数据库快捷键大全

热门文章

  1. java 数字的进制转换
  2. python循环输入若干学生信息网_python最简学生信息系统,练习while
  3. 神奇的go语言(高级应用)
  4. ssm 跨库查询_SSM使用AbstractRoutingDataSource后究竟如何解决跨库事务
  5. easyui分页查询为什么会有下拉框_6个针对MySQL大数据量分页查询优化的锦囊妙计...
  6. java数组长度最大值,javase-获取数组最大值
  7. python抓取websocket_python--websocket数据解析
  8. aspose转pdf不显示中文_word转pdf,迫不得已服务器从linux换成了windows,不完美的完美...
  9. php火的原因,重燃你的PHP安全之火
  10. Windows系统cmd命令检测dll文件