Package: utype
uTypeutype is a data types declaration & parsing library based on Python type annotations,
enforce types and constraints for classes and functions at runtimeDocumentation:https://utype.io中文文档:https://utype.io/zhSource Code:https://github.com/utilmeta/utypeAuthor:@voidZXLLicense: Apache 2.0Core FeaturesEnforce types, data classes, function params and result parsing at runtime based on Python type annotationSupport a variety of constraints, logical operators and flexible parsing optionsHighly extensible, all type transformer can be register, extend and overrideInstallationpipinstall-Uutypeutype requires Python >= 3.7Usage ExampleTypes and constraintsThe utype support to add constraints on types, such asfromutypeimportRule,excclassPositiveInt(int,Rule):gt=0assertPositiveInt(b'3')==3try:PositiveInt(-0.5)exceptexc.ParseErrorase:print(e)"""Constraint: 0 violated"""Data that conforms to the type and constraints will complete the conversion, otherwise will throw a parse error indicating what went wrongParsing dataclassesutype supports the "dataclass" usage that convert a dict or JSON to a class instance, similar topydanticandattrsfromutypeimportSchema,Field,excfromdatetimeimportdatetimeclassUserSchema(Schema):username:str=Field(regex='[0-9a-zA-Z]{3,20}')signup_time:datetime# 1. Valid inputdata={'username':'bob','signup_time':'2022-10-11 10:11:12'}print(UserSchema(**data))#> UserSchema(username='bob', signup_time=datetime.datetime(2022, 10, 11, 10, 11, 12))# 2. Invalid inputtry:UserSchema(username='@invalid',signup_time='2022-10-11 10:11:12')exceptexc.ParseErrorase:print(e)"""parse item: ['username'] failed:Constraint: <regex>: '[0-9a-zA-Z]{3,20}' violated"""After a simple declaration, you can getAutomatic__init__to take input data, perform validation and attribute assignmentProviding__repr__and__str__to get the clearly print output of the instanceparse and protect attribute assignment and deletion to avoid dirty dataParsing functionsutype can also parse function params and resultimportutypefromtypingimportOptionalclassPositiveInt(int,utype.Rule):gt=0classArticleSchema(utype.Schema):id:Optional[PositiveInt]title:str=utype.Field(max_length=100)slug:str=utype.Field(regex=r"[a-z0-9]+(?:-[a-z0-9]+)*")@utype.parsedefget_article(id:PositiveInt=None,title:str='')->ArticleSchema:return{'id':id,'title':title,'slug':'-'.join([''.join(filter(str.isalnum,v))forvintitle.split()]).lower()}print(get_article('3',title=b'My Awesome Article!'))#> ArticleSchema(id=3, title='My Awesome Article!', slug='my-awesome-article')try:get_article('-1')exceptutype.exc.ParseErrorase:print(e)"""parse item: ['id'] failed: Constraint: : 0 violated"""try:get_article(title='*'*101)exceptutype.exc.ParseErrorase:print(e)"""parse item: ['<return>'] failed:parse item: ['title'] failed:Constraint: <max_length>: 100 violated"""You can easily get type checking and code completion of IDEs (such as Pycharm, VS Code) during developmentutype supports not only normal functions, but also generator functions, asynchronous functions, and asynchronous generator functions with the same usageimportutypeimportasynciofromtypingimportAsyncGenerator@utype.parseasyncdefwaiter(rounds:int=utype.Param(gt=0))->AsyncGenerator[int,float]:assertisinstance(rounds,int)i=roundswhilei:wait=yieldstr(i)ifwait:assertisinstance(wait,float)print(f'sleep for:{wait}seconds')awaitasyncio.sleep(wait)i-=1asyncdefwait():wait_gen=waiter('2')asyncforindexinwait_gen:assertisinstance(index,int)try:awaitwait_gen.asend(b'0.5')# sleep for: 0.5 secondsexceptStopAsyncIteration:returnif__name__=='__main__':asyncio.run(wait())TheAsyncGeneratortype is used to annotate the return value of the asynchronous generator, which has two parameters: the type of the value output byyield, type of the value sent byasendAs you can see, the parameters passed to the function and the value received fromyieldwere all converted to the expected type as declaredLogical operation of typeutype supports logical operations on types and data structures using Python-native logical operatorsfromutypeimportSchema,FieldfromtypingimportTupleclassUser(Schema):name:str=Field(max_length=10)age:intone_of_user=User^Tuple[str,int]print(one_of_user({'name':'test','age':'1'}))# > User(name='test', age=1)print(one_of_user([b'test','1']))# > ('test', 1)The example uses the^exclusive or symbol to logically combineUserandTuple[str, int], and the new logical type gains the ability to convert data to one of thoseRegister transformer for typeType transformation and validation strictness required by each project may be different, so in utype, all types support registraton, extension and override, such asfromutypeimportRule,Schema,register_transformerfromtypingimportTypeclassSlug(str,Rule):regex=r"[a-z0-9]+(?:-[a-z0-9]+)*"@register_transformer(Slug)defto_slug(transformer,value,t:Type[Slug]):str_value=transformer(value,str)returnt('-'.join([''.join(filter(str.isalnum,v))forvinstr_value.split()]).lower())classArticleSchema(Schema):slug:Slugprint(dict(ArticleSchema(slug=b'My Awesome Article!')))# > {'slug': 'my-awesome-article'}You can register transformers not only for custom types, but also for basic types (such asstr,int, etc.) Or types in the standard library (such asdatetime,Enum, etc.) To customize the conversion behaviorRoadMap and Contributionutype is still growing, and the following features are planned for implementation in the new versionImprove the handling mechanism of parsing errors, including error handling hook functions, etc.Support the declaration and parse command line parametersSupport for Python generics, type variables, and more type annotation syntaxDevelop Pycharm/VS Code plugin that supports IDE detection and hints for constraints, logical types, and nested typesYou are also welcome to contribute features or submit issues.ApplicationsUtilMeta Python FrameworkUtilMeta Python Framework is a progressive meta-framework for backend applications, which efficiently builds declarative APIs based on the Python type annotation standard, and supports the integration of mainstream Python frameworks as runtime backendHomepage:https://utilmeta.com/pySource Code:https://github.com/utilmeta/utilmeta-pyCommunityutype is a project ofUtilMeta, so you can join the community inDiscordX(Twitter)Reddit中文讨论区