类型化的包装器&pydantic模型;模块加载延迟到初始化。
lazytype的Python项目详细描述
懒散型
编写类型提示,实现可选特性,定义pydantic
模型而不
预先导入延迟,而且无需导入速度慢的模块;使用
lazytype.LazyType
,可以包装一个慢加载类,以便它的模块
在实例化它或运行实际的类型检查之前不会加载。在
也支持Pydantic模型
通过LazyField
接口,但不需要使用Pydantic
已安装以使用LazyType
s
安装
对于用户:
pip install lazytype
(可选)确保pydantic
是用pydantic
选项安装的(如果
计划使用LazyField
s):
对于开发人员,请克隆此存储库,更改到其目录,然后运行:
flit install --symlink
示例
常规LazyTypes
接口与包装对象相同:
>>>a=LazyType['numpy.ndarray']((3,2))>>>a<Lazyarray([[-1.49166815e-154,-2.68679856e+154],[1.48219694e-323,0.00000000e+000],[0.00000000e+000,4.17201348e-309]])>>>>a._instancearray([[-2.00000000e+000,2.32036240e+077],[1.48219694e-323,0.00000000e+000],[0.00000000e+000,4.17201348e-309]])>>>a[:]=0>>>aarray([[0.,0.],[0.,0.],[0.,0.]])>>>a.dtypedtype('float64')>>>isinstance(a._instance,type(a))True
您可以选择要求在上运行对模块可用性的检查 定义时间:
# this works if you have "numpy" installed>>>LazyArray=LazyType['numpy.ndarray','strict':True]lazytype.Lazyndarray# this doesn't (unless you have a package called "numpay"...)>>>LazyArray=LazyType['numpay.ndarray','strict':True]ImportError:Strictcheckformodulenumpayavailabilityfailed
pydantic
包含LazyField
s的字段
您还可以将LazyType
s与Pydantic模型一起使用来指定数据类型和
验证器。这需要LazyField
类提供一些额外的方法;
您可以指定任何要用于架构的built-in Pydantic
field-type
验证,后跟用于创建新的
LazyType
。这允许您将现有字段类型映射到自定义,
慢速加载字段类型,它可以简单地接受相同的输入参数,全部
在你的模型被实例化之前不加载被包装的类的模块。在
使用内置的
datetime
字符串验证器:
>>>fromdatetimeimportdatetime>>>LazyField[datetime,'astropy.time.Time','strict':True]lazytype.LazyFieldTime
实际使用pydantic
模型中的字段:
>>>frompydanticimportBaseModel>>>classLazyTest(BaseModel):...foo:str...time:LazyField[datetime,'astropy.time.Time','strict':True]
请参见生成模型的JSON架构:
>>>LazyTest.schema(){'title':'LazyTest','type':'object','properties':{'foo':{'title':'Foo','type':'string'},'time':{'title':'Time','type':'string','format':'date-time'}},'required':['foo','time']}
实际实例化一些内容,强制astropy.time.Time
加载:
>>>t=LazyTest(foo='bar',time='2019-11-29 13:40:29.197')>>>t.time<Lazy<Timeobject:scale='utc'format='iso'value=2019-11-2913:40:29.197>>>>>t.time.gps1259070047.197
提供额外的模式注释,例如提供示例输入 价值观:
>>>classLazyTest(BaseModel):...foo:str...time:LazyField[str::{'example':'2019-11-29 13:40:29.197'},...'astropy.time.Time','strict':True]>>>LazyTest.schema(){'title':'LazyTest','type':'object','properties':{'foo':{'title':'Foo','type':'string'},'time':{'title':'Time','type':'string','example':'2019-11-29 13:40:29.197'}},'required':['foo','time']}
- 项目
标签: