Package: typeannotations
https://github.com/ceronman/typeannotationsAboutThetypeannotationsmodule provides a set of tools for type checking and
type inference of Python code. It also a provides a set of types useful for
annotating functions and objects.These tools are mainly designed to be used by static analyzers such as linters,
code completion libraries and IDEs. Additionally, decorators for making
run-time checks are provided. Run-time type checking is not always a good
idea in Python, but in some cases it can be very useful.Run-time type checking.Thetypecheckeddecorator can be used to check types specified in function
annotations. For example:>>>@typechecked...deftest(a:int)->int:...returna...>>>test(1)1>>>test('string')Traceback (most recent call last):...TypeError:Incorrect type for "a"Structural interfacesTheInterfaceclass allows you to define interfaces that are checked
dynamically. You don’t have to explicitly indicate when an object or class
implements a givenInterface. If an object provides the methods and
attributes specified in theInterface, it’s considered a valid
implementation.For example, let’s define a simple interface:>>>classPerson(Interface):...name=str...age=int...defsay_hello(name:str)->str:...passAny object defining those thename,ageandsay_hello()members is
a valid implementation of that interface. For example:>>>classDeveloper:...def__init__(self,name,age):...self.name=name...self.age=age...defsay_hello(self,name:str)->str:...return'hello '+name...>>>isinstance(Developer('bill',20),Person)TrueThis also works with built-in types:>>>classIterableWithLen(Interface):...def__iter__():...pass...def__len__():...pass...>>>isinstance([],IterableWithLen)True>>>isinstance({},IterableWithLen)True>>>isinstance(1,IterableWithLen)FalseTypedefsAtypedefis similar to anInterfaceexcept that it defines a single
function signature. This is useful for defining callbacks. For example:>>>@typedef...defcallback(event:Event)->bool:...pass...Then it’s possible to check if a function implements the same signature:>>>defhandler(event:MouseEvent)->bool:...print('click')...returnTrue...>>>isinstance(handler,callback)True>>>isinstance(lambda:True,callback)FalseNote thatMouseEventis a subclass ofEvent.Type unionsAunionis a collection of types and it’s a type itself. An object is an
instance of aunionif it’s an instance of any of the elements in the union.
For example:>>>NumberOrString=union(int,str)>>>isinstance(1,NumberOrString)True>>>isinstance('string',NumberOrString)True>>>issubclass(int,NumberOrString)True>>>issubclass(str,NumberOrString)TruePredicatesApredicateis a special type defined by a function that takes an object
and returnsTrueorFalseindicating if the object implements the type.
For example:>>>Positive=predicate(lambdax:x>0)>>>isinstance(1,Positive)True>>>isinstance(0,Positive)FalsePredicates can also be defined using a decorator:>>>@predicate...defEven(object):...returnobject%2==0Predicates can also be combined using the&`operator:>>>EvenAndPositive=Even&PositivePredicates are useful for defining contracts:>>>Positive=predicate(lambdax:x>0)>>>@typechecked...defsqrt(n:Positive):......>>>sqrt(-1)Traceback (most recent call last):...TypeError:Incorrect type for "n"TheoptionalpredicateTheoptionalpredicate indicates that the object must be from the given type
orNone. For example:>>>isinstance(1,optional(int))True>>>isinstance(None,optional(int))TrueAnd checking types at runtime:>>>@typechecked...defgreet(name:optional(str)=None):...ifnameisNone:...print('hello stranger')...else:...print('hello{0}'.format(name))...>>>greet()hello stranger>>>greet('bill')hello billTheonlypredicateTheonlypredicate indicates that an object canonlybe of the specified
type, and not of any of its super classes. For example:>>>isinstance(True,only(bool))True>>>isinstance(1,only(bool))FalseNote that in Pythonboolis a sublcass ofint.TheoptionspredicateTheoptionspredicate indicates that the value of an object must be one of
the given options. For example:>>>FileMode=options('r','w','a','r+','w+','a+')>>>isinstance('w',FileMode)True>>>isinstance('x',FileMode)FalseThis is useful when defining a function:>>>@typecheck...defopen(filename:str,mode:options('w','a')):......To be implemented:Collections definitions:typedict({str:int})typeseq([int])typeseq(set(int))typeseq((int,))...Function overloading@overloaddefisinstance(object,t:type):...@overloaddefisinstance(object,t:tuple):...Annotate existing functions and libraries@annotate('builtins.open')defopen_annotated(file:str,mode:options('r','w','a','r+','w+','a+'),buffering:optional(int))->IOBase:passLicenseLicensed under the Apache License, Version 2.0 (the “License”);you may not use this file except in compliance with the License.You may obtain a copy of the License athttp://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed under the License is distributed on an “AS IS” BASIS,WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.  See the License for the specific languagegoverning permissions and limitations under the License.