包含有用的python类和magic类型的工具箱。
nr.types的Python项目详细描述
数量类型
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.abc
或collections
的别名(模块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