[Python-ideas] Delay evaluation of annotations

Nick Coghlan ncoghlan at gmail.com
Thu Sep 22 21:17:54 EDT 2016


On 23 September 2016 at 05:58, 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.

That doesn't work, as "self" hasn't been bound yet when the
annotations are evaluated, just like A hasn't been bound yet (since it
doesn't exist until *after* the class body finishes executing).

As others have noted, the general idea of allowing either a
placeholder name or the class name to refer to a suitable type
annotation is fine, though - that would be a matter of implicitly
injecting that name into the class namespace after calling
__prepare__, and ensuring the compiler is aware of that behaviour,
just as we inject __class__ as a nonlocal reference into method bodies
that reference "super" or "__class__".

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list