Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make type aliases for type constructors in python using the typing module?

Tags:

python

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.

like image 231
Sam De Meyer Avatar asked Apr 17 '18 21:04

Sam De Meyer


People also ask

What is the use of typing module in Python?

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.

What is a type alias Python?

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.

Does Python 3.6 support type hints?

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.

What is type alias?

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.


1 Answers

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
like image 112
TwistedSim Avatar answered Nov 20 '22 11:11

TwistedSim