包含有用的python类和magic类型的工具箱。

nr.types的Python项目详细描述


数量类型

CircleCI

nr.types包为日常工作提供了许多有用的数据类型 python编程。它与Python2.7和 Python3。

安装

pip install nr.types

运行测试

pip install -e .[test]
pytest --cov=./src/nr

api

nr.types.NotSet

None是可接受值的情况下,NotSet单例非常有用 对于一个参数,需要有一个额外的状态来定义 参数为“未设置”。

nr.types.abc

collections.abccollections的别名(模块six不 提供这些模块的移动)。

nr.types.functools

帮助处理python函数内部的工具,如闭包、代码 以及功能对象。

示例:
importnr.types.functoolsasftdeftest(value):defx():returnvaluereturnxx=test(42)assertx()==42y=ft.copy_function(x,closure={'value':99})asserty()==99

nr.types.generic

允许您实现泛型类型,即带参数的类。

示例:
fromnr.typesimportgenericclassHashDict(generic.Generic['key_hash']):def__init__(self):generic.assert_initialized(self)self.data={}def__getitem__(self,key):returnself.data[self.key_hash(key)]def__setitem__(self,key,value):self.data[self.key_hash(key)]=valueUnsafeHashDict=HashDict[hash]

nr.types.interface

类似于zope.interface,但与python 3兼容且不太神奇。

示例:
fromnr.types.interfaceimportInterface,Implementation,implements,attrclassIFoo(Interface):""" The foo interface. """x=attr("""Some attribute.""")defbar(self,q,r=None):""" The bar function. """assertset(IFoo)==set(['x','bar'])assertnothasattr(IFoo,'x')assertnothasattr(IFoo,'bar')assertIFoo['x'].name=='x'assertIFoo['bar'].name=='bar'@implements(IFoo)classFoo(object):def__init__(self,x=None):self.x=xdefbar(self,q,r=None):returnq,r,self.xassertissubclass(Foo,Implementation)assertIFoo.implemented_by(Foo)assertIFoo.provided_by(Foo())assertlist(IFoo.implementations())==[Foo]assertFoo(42).x==42

nr.types.maps

提供以下映射(以及与映射相关的)实现:

  • OrderedDict
  • ObjectAsDict
  • ObjectFromDict
  • ChainDict(使用maps.chain()
  • HashDict[hash_func]
  • ValueIterableDict

nr.types.meta

提供有用的元类,例如InlineMetaclass

示例:
fromnr.types.metaimportInlineMetaclassBaseclassMyClass(InlineMetaclassBase):def__metainit__(self,name,bases,attr):print('MyClass constructed!')self.value='foo'assertMyClass.value=='foo'

nr.types.moduletools

提供一些用于处理模块的工具。目前只提供 make_inheritable()函数,可以从模块内部使用到 使模块对象本身可用作父类。

# myclass.pyclassMyClass(object):passmake_inheritable(__name__)# test.pyimportmyclassclassMySubclass(myclass):passassertissubclass(MySubclass,myclass.MyClass)

nr.types.proxy

提供proxy类,该类是可调用的包装器。任何一种 对代理对象的访问被重定向到 可呼叫。

代理类示例:
fromnr.typesimportproxycount=0@proxydefauto_increment():globalcountcount+=1returncountassertauto_increment==1assertauto_increment==2assertauto_increment+10==13
代理类示例:
fromnr.types.proxyimportlazy_proxycount=0@lazy_proxydefnot_incrementing():globalcountcount+=1returncountassertnot_incrementing==1assertnot_incrementing==1assertnot_incrementing==1

nr.types.record

类似于namedtuple,但可变,支持关键字参数, 类型声明和默认值。支持多种形式的声明 一个记录,例如通过python 3.6+类级别注释,指定一个类级别 __fields__成员或通过创建record.Field()声明属性 物体。

示例:
importrandomfromnr.typesimportrecordclassPerson(record.Record):name:strmail:str=Noneage:int=lambda:random.randint(10,50)p=Person('John Smith')assertp.name=='John Smith'assertp.mailisNoneassert10<=p.age<=50
备选方案:
importrandomfromnr.typesimportrecordclassPerson(record.Record):name=record.Field(str)mail=record.Field(str,None)age=record.Field(str,lambda:random.randint(10,50))classPerson(record.Record):__fields__=[('name',str),('mail',str,None),('age',str,lambda:random.randint(10,50)),]Person=record.create_record('Person',[('name',str),record.Field.with_name('mail',str,None),('age',str,lambda:random.randint(10,50))])Person=record.create_record('Person',{'name':record.Field(str),'mail':record.Field(str,None),'age':record.Field(str,lambda:random.randint(10,50))})assertlist(Person.__fields__.keys())==['name','mail','age']

nr.types.sets

目前只提供OrderedSet实现。

nr.types.stream

示例:
fromnr.typesimportstreamstream(range(10)).map(lambdax:x*2)stream.map(range(10),lambdax:x*2)

nr.types.structured

示例:
fromnr.typesimportstructuredPerson=structured.ForwardDecl('Person')People=structured.translate_field_type({Person})classPerson(structured.Object):name=structured.ObjectKeyField()age=structured.Field(int)numbers=structured.Field([str])data={'John':{'age':52,'numbers':['+1 123 5423435']},'Barbara':{'age':29,'numbers':['+44 1523/5325323']}}people=structured.extract(data,People)assertpeople['John']==Person('John',52,['+1 123 5423435'])assertpeople['Barbara']==Person('Barbara',29,['+44 1523/5325323'])

nr.types.sumtype

示例:
fromnr.typesimportrecord,sumtypeclassFilter(sumtype):# Three ways to define constructors.# 1)Date=sumtype.constructor(record.create_record('Date','min,max'))# 2)Keyword=sumtype.constructor('text')# 3)@sumtype.constructorclassDuration(sumtype.record):value=sumtype.field(int,default=3600)defto_hours(self):returnself.value/3600.0# Enrich constructors with members.@sumtype.member_of([Date,Keyword])defonly_on_date_or_keyword(self):return'The answer is 42'f=Filter.Keyword('building')assertisinstance(f,Filter)assertf.is_keyword()assertf.text=='building'asserthasattr(f,'only_on_date_or_keyword')assertf.only_on_date_or_keyword()=='The answer is 42'f=Filter.Date(10,42)assertisinstance(f,Filter)assertf.is_date()assert(f.min,f.max)==(10,42)asserthasattr(f,'only_on_date_or_keyword')assertf.only_on_date_or_keyword()=='The answer is 42'f=Filter.Duration()assertisinstance(f,Filter)assertf.is_duration()assertf.value==3600assertnothasattr(f,'only_on_date_or_keyword')f=Filter.Duration(value=4759)assertf.value==4759assertf.to_hours()==(4759/3600.0)

版权所有©Niklas Rosenstein 2019

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java从CQ5获取搜索词建议。5指数   java如何创建在一列中嵌入按钮的tableview?   java使用postman为SLACK生成身份验证令牌   java选择具有最大日期休眠的行   java Jenkins在部署SpringMVC JPA webapp MySQL连接时未释放HikariCP   修改JSF UIComponent时未更改java实体属性   java Sprite图像出现拉伸且质量差,无法获得正确的位置GDXLib   java如何将分数正确地分配给玩家?   java如果“private static int”实例变量未初始化,它是否等于零?   java这个LimitedInputStream正确吗?   java如何调用使用JNA返回字符串的Delphi函数?   java JPA更新实体,包括实体列表   java制作流副本的最有效方法是什么?   java无法导入安卓支持IntelliJ项目   java分别乘以负音值和正音值   每秒验证/断言的java JMeter请求数