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
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to