[Python-ideas] function annotation enhancement
jelle.zijlstra at gmail.com
Tue Mar 19 17:32:43 EDT 2019
Your proposed syntax is hard to implement, because it would require
invasive syntax changes to the language itself. That's probably not worth
However, there are other ways to achieve what you're looking for that don't
require changing the language itself. This issue has some proposals:
El mar., 19 mar. 2019 a las 14:25, Tim Mitchell (<
tim.mitchell.chch at gmail.com>) escribió:
> 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 annotations
> 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:
> For example
> class MyClass(object):
> def my_prop: int(self)
> return 10
> c = MyClass()
> Then c.my_prop would be type hinted as an integer.
> What do people think?
> Python-ideas mailing list
> Python-ideas at python.org
> Code of Conduct: http://python.org/psf/codeofconduct/
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas