包含有用的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 Android:在内部存储器中保存两个同名位图   java如何获取每个月的记录?   java错误:找不到com。安卓工具。构建:渐变:3.2.1   Java反射,如何使用构造函数获取newInstance是一个很重要的问题。类别ex:Class<Customer>customerClass   java具体类不使用泛型标识符编译   java InputStream在Apache FileUpload API中关闭   java自动隐藏任务栏和最大屏幕空间   java端点返回对象而不是直接JSON   java打印BST的直径   在Java中将节点追加到xml   java如何在Jersey中注册静态类?   java如何修改for循环,使其不比较第一个循环和最后一个循环,而是将所有其他循环与最后一个循环进行比较?   java扩展主机意外终止(vscode)   如何使用Java进程读取mysql控制台输出   java从现有列表创建元素列表   java将数据流式传输到BigQuery新表中?   java如何从绑定结果验证失败返回错误响应?