[Python-ideas] function annotation enhancement

Tim Mitchell 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):
   pass

however it does not work for the callback itself, I have to repeat myself

def my_callback(a: int, b: str) -> None:
    pass

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):
    pass

any further parameter annotations would be disallowed:

def my_callback: CallbackType(a: int, b: str):   # Syntax error - duplicate
annotations
    pass


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
    pass


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:
For example

class MyClass(object):
    @property
    def my_prop: int(self)
        return 10

c = MyClass()
Then c.my_prop would be type hinted as an integer.

What do people think?
Cheers
Tim
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20190320/8964fdf2/attachment.html>


More information about the Python-ideas mailing list