Sam De Meyer
Sam De Meyer

Reputation: 2381

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

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.

Upvotes: 19

Views: 4169

Answers (1)

TwistedSim
TwistedSim

Reputation: 2030

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

Upvotes: 9

Related Questions