[Python-ideas] Delay evaluation of annotations

אלעזר elazarg at gmail.com
Thu Sep 22 17:10:03 EDT 2016


On Fri, Sep 23, 2016 at 12:05 AM Ivan Levkivskyi <levkivskyi at gmail.com>
wrote:

> On 22 September 2016 at 22:02, אלעזר <elazarg at gmail.com> wrote:
>
>> On Thu, Sep 22, 2016 at 10:58 PM David Mertz <mertz at gnosis.cx> wrote:
>>
>>> On Thu, Sep 22, 2016 at 12:35 PM, אלעזר <elazarg at gmail.com> wrote:
>>>
>>>> I think we're talking about different things here. I just referred to
>>>> the common need to use the name of the current class in type annotation
>>>>
>>>> class A:
>>>>     def add(self, other: A) -> A: ...
>>>>
>>>
>>> Yeah, I find the need for using the string "A" here a wart. Rather than
>>> change the entire semantics of annotations, it feels like a placeholder for
>>> this meaning would be better.  E.g.:
>>>
>>> class A:
>>>     def __add__(self, other: CLS) -> CLS: ...
>>>
>>> A static checker could do the magic of recognizing that special name
>>> easily enough (no harder than recognizing the quoted string).  At runtime
>>> 'CLS' could either just be a singleton with no other behavior... or perhaps
>>> it could be some sort of magic introspection object.  It's more verbose,
>>> but you can also spell it now as:
>>>
>>> class A:
>>>     def __add__(self, other: type(self)) -> type(self): ...
>>>
>>> That's a little ugly, but it expresses the semantics we want.
>>>
>>
> Concerning the __add__ method, I think a more typical type for it is
>
> T = TypeVar('T', bound='A')
>
> class A:
>     def __add__(self: T, other: T) -> T: ...
>
> There is a plan to support this in one of next releases of mypy.
>
> And now the reader should understand what is TypeVar, and you still have
the string there. Not that I'm saying it's a bad solution, but it fits pyi
files more than average-programmer-code.


> In general I think it is a bit early to judge what would be the best
> solution for forward references.
> (there are related issues like performance drop etc). More evidence is
> needed to decide a way forward.
>

The problem with waiting for more evidence is that more code will break if
the change require such breakage. At least side-effect in annotation
expressions should be "deprecated" and not guarantee when it happen, how
many times, etc.

Elazar
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20160922/17e4b45a/attachment.html>


More information about the Python-ideas mailing list