Since python version 3.5, you can use type hints to indicate what type of arguments a function is expecting. I find these type hints extremely valuable for documentation purposes, so I try to use them as much as I can. They also help the linter and therefore regularly save me from bugs introduced by code changes.
For example, in my code I have a few functions which take a zero-argument function as an argument. E.g.:
def onReady(f: Callable[[], Any]) -> None:
...
Or
def checkIfReady(f: Callable[[], Bool]) -> None:
...
What I would like to do is make a type alias like so (the code below is not valid python):
Action[A] = Callable[[], A]
And then I could shorten my types for the arguments above:
def onReady(f: Action[Any]) -> None:
...
I know I can make a type alias for a specific instance, e.g.:
ActionBool = Callable[[], bool]
And I know of the existance of NewType
in the typing
module, but neither of these seem to generalize to higher order types.
The typing module provides us with Type Aliases, which is defined by assigning a type to the alias. In the above snippet, Vector is an alias, which stands for a list of floating point values. We can type hint at an alias, which is what the above program is doing.
A type alias is defined by assigning the type to the alias. In this example, Vector and list[float] will be treated as interchangeable synonyms: Vector = list[float] def scale(scalar: float, vector: Vector) -> Vector: return [scalar * num for num in vector] # typechecks; a list of floats qualifies as a Vector.
This module supports type hints as specified by PEP 484 and PEP 526. The most fundamental support consists of the types Any , Union , Tuple , Callable , TypeVar , and Generic . For full specification please see PEP 484. For a simplified introduction to type hints see PEP 483.
Type aliases Type aliases provide alternative names for existing types. If the type name is too long you can introduce a different shorter name and use the new one instead. It's useful to shorten long generic types. For instance, it's often tempting to shrink collection types: typealias NodeSet = Set<Network.
I think i've found the simplest solution. According to PEP 484, this is valid:
T = TypeVar('T') # or TypeVar('T', int, float, bool, str)
Action = Callable[[], T]
def onReady(f: Action[Any]) -> None:
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With