Wrapper around getmro from inspect to also support typing types.
Types
Type
Description
T
A generic Type var.
KT
A Type var for keys in a dict.
VT
A type var for values in a dict.
Empty
The type of emptiness (= Parameter.empty).
Unknown
The type of something unknown.
Module
The type of a module.
NoneType
The type of None.
EllipsisType
The type of ....
Decorators
hintable
This decorator allows one to capture the type hint of a variable that calls a function. If no hint is provided, None
is passed as a value for hint.
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, your hintable function does indeed return a value of that type.
@hintable
def cast(arg: Any, hint: Type[T]) -> T:
return hint(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: str
Classes
SubscriptableType
This metaclass allows a type to become subscriptable.
Anything that has the attributes defined in Something with the right type is
considered an instance of that Something (classes, objects, even modules...).
The builtin isinstance is supported as well as typish.instance_of.
ClsDict
A 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):
...
def func(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.
ClsFunction
A callable that uses ClsDict to call the right function.
Below is the same example as above, but slightly modified in
that it uses ClsFunction.
Example:
def _handle_str(item):
...
def _handle_int(item):
...
def func(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)
Literal
A backwards compatible variant of typing.Literal (Python3.8). When importing
Literal from typish, you will get the typing.Literal if it is available.
Alternatives
Use instead of typish: tools that do the same job, closest first.