On 23 September 2016 at 12:05, אלעזר <elaz...@gmail.com> wrote:
> On Fri, Sep 23, 2016 at 4:17 AM Nick Coghlan <ncogh...@gmail.com> wrote:
> ...
>> 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__".
> Just to be sure I understand, will the following work?
> class A:
>     def repeat(n: int) -> List[A]: pass

Right now? No - you'll get a name error on the "A", just as you would
if you tried to reference it as a default argument:

  >>> class A:
  ...     def side_effects_ahead(arg: print(A) = print(A)) -> print(A): pass
  Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 2, in A
  NameError: name 'A' is not defined

And that's the problem with using the class name in method annotations
in the class body: they're evaluated eagerly, so they'd fail at
runtime, even if the typecheckers were updated to understand them.

Rather than switching annotations to being evaluated lazilly in the
general case, one of the solutions being suggested is that *by
default*, the class name could implicitly be bound in the body of the
class definition to some useful placeholder, which can already be done
explicitly today:

  >>> class A:
  ...     A = "placeholder"
  ...     def side_effects_ahead(arg: print(A) = print(A)) -> print(A): pass

Since method bodies don't see class level name bindings (by design),
such an approach would have the effect of "A" referring to the
placeholder in the class body (including for annotations and default
arguments), but to the class itself in method bodies.

I don't think this is an urgent problem (since the "A"-as-a-string
spelling works today without any runtime changes), but it's worth
keeping an eye on as folks gain more experience with annotations and
the factors affecting their readability.


Nick Coghlan   |   ncogh...@gmail.com   |   Brisbane, Australia
Python-ideas mailing list
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to