[Python-ideas] Proposal: Use mypy syntax for function annotations
Cem Karan
cfkaran2 at gmail.com
Mon Aug 25 12:57:23 CEST 2014
On Aug 25, 2014, at 6:20 AM, Ed Kellett <edk141 at gmail.com> wrote:
> On 25 August 2014 07:18, Terry Reedy <tjreedy at udel.edu> wrote:
>> On 8/24/2014 11:12 PM, Guido van Rossum wrote:
>>
>>> Finally, I would actually be okay if we found a way to let type hints
>>> and other annotations coexist -- I just prefer type hints to be the
>>> default use, since I see them as much more generally useful than all
>>> other uses combined.
>>
>>
>> I believe co-existence is possible, but the details will depend on the form
>> type hints take. First, other annotations should be easily distinguished
>> from type hints. Second, other annotations that would interfere with the
>> runtime use of __annotations__ should be pulled out by a decorator and
>> possibly moved to another attribute specific to the decorator (such as
>> '_deco_name').
>
> … or we could have a decorator for type hints, and ascribe no new
> meaning at all to __annotations__. Or assume __annotations__ contains
> type hints iff all the annotations present are instances of typing.*.
> That might be better anyway, since a decorator could then add (or
> augment) type information without assigning to __annotations__ (which
> would be weird).
>
> Even if conveying type information is the most useful use of
> annotations, there's no reason it can't be explicit (and consistent
> with other uses of annotations).
I'm going to beat on my drum some more, but if annotations are dictionaries, where the keys are objects known to be associated with the type checker, then we don't have to guess, we'll know. E.g.:
"""
# type_checker.py
class type_checker(object):
# decorator magic
TYPE_CHECKER = type_checker()
"""
"""
# Your file
from type_checker import TYPE_CHECKER
@TYPE_CHECKER(a, int)
def foo(a):
pass
"""
which is morally equivalent to:
"""
from type_checker import TYPE_CHECKER
def foo(a: {TYPE_CHECKER: int}):
pass
"""
Chris Angelico pointed this trick out to me, and I think it's a good one. Assuming the type checker has enough brains to check and ensure that TYPE_CHECKER is never reassigned, it is guaranteed by the runtime system that TYPE_CHECKER is unique, which means that it can do the moral equivalent of 'TYPE_CHECKER in foo.__annotations__['a']'. That gives a VERY simple method of knowing what the annotations are being used for.
Thanks,
Cem Karan
More information about the Python-ideas
mailing list