Package: typish
TypishFunctions for thorough checks on typesInstance checks considering genericsTypesafe Duck-typingExample>>>fromtypingimportIterable>>>fromtypishimportinstance_of>>>instance_of([1,2,3],Iterable[int])TrueInstallationpip install typishContentFunctionsFunctionDescriptionsubclass_of(cls: type, *args: type) -> boolReturns whetherclsis a sub type ofalltypes inargsinstance_of(obj: object, *args: type) -> boolReturns whetherclsis an instance ofalltypes inargsget_origin(t: type) -> typeReturn the "origin" of a generic type. E.g.get_origin(List[str])giveslist.get_args(t: type) -> typing.Tuple[type, ...]Return the arguments of a generic type. E.g.get_args(List[str])gives(str, ).get_alias(cls: T) -> typing.Optional[T]Return thetypingalias for a type. E.gget_alias(list)givesList.get_type(inst: T, use_union: bool = False) -> typing.Type[T]Return the (generic) type of an instance. E.g. a list of ints will giveList[int].common_ancestor(*args: object) -> typeReturn the closest common ancestor of the given instances.common_ancestor_of_types(*args: type) -> typeReturn the closest common ancestor of the given classes.get_args_and_return_type(hint: typing.Type[typing.Callable]) -> typing.Tuple[typing.Optional[typing.Tuple[type]], typing.Optional[type]]Get the argument types and the return type of a callable type hint (e.g.Callable[[int], str]).get_type_hints_of_callable(func: typing.Callable) -> typing.Dict[str, type]Return the type hints of the parameters of the given callable.is_type_annotation(item: typing.Any) -> boolReturns whetheritemis atypeor atypingtype.is_from_typing(cls: type) -> boolReturns whetherclsis from thetypingmodule.is_optional_type(cls: type) -> boolReturns whetherclsis considered to be an optional type.get_mro(obj: typing.Any) -> typing.Tuple[type, ...]Wrapper aroundgetmrofrominspectto also supporttypingtypes.TypesTypeDescriptionTA generic Type var.KTA Type var for keys in a dict.VTA type var for values in a dict.EmptyThe type of emptiness (=Parameter.empty).UnknownThe type of something unknown.ModuleThe type of a module.NoneTypeThe type ofNone.EllipsisTypeThe type of....DecoratorshintableThis decorator allows one to capture the type hint of a variable that calls a function. If no hint is provided,Noneis passed as a value forhint.Just remember: with great power comes great responsibility. Use this functionality wisely. You may want to make sure
that if you hinted a variable with a certain type, yourhintablefunction does indeed return a value of that type.@hintabledefcast(arg:Any,hint:Type[T])->T:returnhint(arg)# The type hint on x is passed to cast:x:int=cast('42')# It works with MyPy hints as well:y=cast('42')# type: int# Not something you would normally do, but the type hint takes precedence:z:int=cast('42')# type: strClassesSubscriptableTypeThis metaclass allows a type to become subscriptable.Example:classMyClass(metaclass=SubscriptableType):...Now you can do:MyClass2=MyClass['some args']print(MyClass2.__args__)print(MyClass2.__origin__)Output:some args
<class '__main__.MyClass'>SomethingDefine an interface withtypish.Something.Example:Duck=Something['walk':Callable[[],None],'quack':Callable[[],None]]Anything that has the attributes defined inSomethingwith the right type is
considered an instance of thatSomething(classes, objects, even modules...).The builtinisinstanceis supported as well astypish.instance_of.ClsDictA dictionary that uses instance checking to determine which value to return.
It only accepts types as keys.This is particularly useful when a function accepts multiple types for an
argument and you want to split the implementation into separate functions.Example:def_handle_str(item):...def_handle_int(item):...deffunc(item):# Suppose item can be a string or an int, you can use ClsDict to# pick a handler function.cd=ClsDict({str:_handle_str,int:_handle_int,})handler=cd[item]# Pick the right handler.handler(item)# Call that handler.ClsFunctionA callable that usesClsDictto call the right function.
Below is the same example as above, but slightly modified in
that it usesClsFunction.Example:def_handle_str(item):...def_handle_int(item):...deffunc(item):# Suppose item can be a string or an int, you can use ClsFunction to# delegate to the right handler function.function=ClsFunction({str:_handle_str,int:_handle_int,})function(item)LiteralA backwards compatible variant of typing.Literal (Python3.8). When importingLiteralfromtypish, you will get thetyping.Literalif it is available.