[Python-ideas] function annotation enhancement
tim.mitchell.chch at gmail.com
Tue Mar 19 17:24:46 EDT 2019
I would like to propose an enhancement to function annotations. Here is
the motivating use case:
When using callbacks I would like to declare the signature once as a type
alias and use it to type hint both the function accepting the callback and
the callbacks themselves.
Currently I can declare the function signare
CallbackType = Callable[[int, str], Any]
and use it for the function/method accepting the callback
def my_func(callabck: CallbackType):
however it does not work for the callback itself, I have to repeat myself
def my_callback(a: int, b: str) -> None:
and if I change the signature in CallbackType the typechecker has to know
that my_callback will be passed to my_func in order to detect the error.
I propose to add a new syntax that declares the type of the function after
the function name.
def my_callback: CallbackType(a, b):
any further parameter annotations would be disallowed:
def my_callback: CallbackType(a: int, b: str): # Syntax error - duplicate
If the function parameters do not match the type signare, type hinters
would flag this as a type mismatch.
def my_callback: CallbackType(a): # type mismatch
My original thought was that if CallbackType was not a Callable this would
also be a type error.
However I have since realized this could be used for declaring the return
type of properties:
def my_prop: int(self)
c = MyClass()
Then c.my_prop would be type hinted as an integer.
What do people think?
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas