未提供项目说明
jashin的Python项目详细描述
贾欣
各种Python实用程序。在
在贾欣·迪克塔特模块
jashin.dictattr
提供ItemAttr
和{
像这样包装字典
userdict={"name":"test user","age":20}
您可以使用ItemAttr
和{
ItemAttr
支持嵌套对象。在
companydict={"CEO":{name:"A CEO",age:"21",}"COO":{name:"A COO",age:"31",}}
要包装上面的字典,可以提供Company
类。在
classCompany(DictModel):CEO=ItemAttr(User)COO=ItemAttr(User)company=Company(companydict)print(company.CEO.name)# prints 'A CEO'
DictModel
类不是必需的,但提供它是为了避免样板代码。ItemAttr
使用__dictattr_get__
方法处理任何类。在
classUser:name=ItemAttr()age=ItemAttr()def__init__(self,record):self._recdict=recorddef__dictattr_get__(self):"Called by ItemAttr object to get dictionary"returnself._recdict
支持类型批注。在
classUser(DictModel):name=ItemAttr[str]()# Explicity specify typeage=ItemAttr(int)# Inferred from `int` function.user.name="name"# OKuser.age="30"# Incompatible types in assignment# The right hand side expression has type "str",# but 'age' attribute has type "int".
在贾欣。消失了模块
jashin.elapsed
测量任意部分的运行时间。在
节可以由with
块指定。在
>>>fromjashin.elapsedimportElapsed>>>e=Elapsed()>>>deftest():...a=1...foriinrange(10):...withe("section 1"):...a+=1......withe("section 2"):...a+=1...>>>test()>>>e.print()section1:n:10sum:0.00002ave:0.00000section2:n:10sum:0.00002ave:0.00000
或者通过一对begin(name)
和end()
方法。在
>>>fromjashin.elapsedimportElapsed>>>e=Elapsed()>>>deftest2():...a=1...foriinrange(10):...e.begin("section A"):...a+=1...e.end()......e.begin("section B"):...a+=1...e.end()...>>>test2()>>>e.print()sectionA:n:10sum:0.00002ave:0.00000sectionB:n:10sum:0.00002ave:0.00000
在jashin.jsondefault公司模块
要将任意对象序列化为JSON,应该定义default
函数。在
defconverter(obj):ifisinstance(obj,set):returnlist[obj]ifisinstance(obj,datetime):returnobj.isoformat()...print(json.dumps(obj,default=converter))
这太乏味了。jashin.jsondefault.common
提供了使常用类型的对象JSON可序列化的通用函数。在
fromjashinimportjsondefaultrepo=jsondefault.common()print(json.dumps(obj,default=repo)
由于jashin.jsondefault.common
是一个single-dispatch generic function,因此可以扩展它来转换自定义对象。在
fromjashinimportjsondefault@dataclassdefFoo:attr1:int=100repo=jsondefault.common()@repo.register(Foo)defconv_foo(obj):return{'attr1':obj.foo}print(json.dumps(object,default=repo)
- 项目
标签: