[Python-Dev] PEP 563: Postponed Evaluation of Annotations

Ivan Levkivskyi levkivskyi at gmail.com
Thu Nov 2 15:32:06 EDT 2017


On 1 November 2017 at 23:48, Lukasz Langa <lukasz at langa.pl> wrote:

> Runtime annotation resolution and class decorators
> --------------------------------------------------
>
> Metaclasses and class decorators that need to resolve annotations for
> the current class will fail for annotations that use the name of the
> current class.  Example::
>
>     def class_decorator(cls):
>         annotations = get_type_hints(cls)  # raises NameError on 'C'
>         print(f'Annotations for {cls}: {annotations}')
>         return cls
>
>     @class_decorator
>     class C:
>         singleton: 'C' = None
>
> This was already true before this PEP.  The class decorator acts on
> the class before it's assigned a name in the current definition scope.
>
>
Just a random idea: maybe this can be resolved by just updating the localns
before calling get_type_hints() like this:

  localns = locals().copy()
  localns.update({cls.__name__: cls})


In general I like how the PEP is written now. I maybe would add examples
for this

> the cases listed above might be worked around by placing the usage
> in a if TYPE_CHECKING: block.
> ...
> For named tuples, using the new class definition syntax introduced in
Python 3.6 solves the issue.

actually showing something like

  if TYPE_CHECKING:
      Alias = List[Tuple[int, SomeClass]]

  class NT(NamedTuple):
      one: SomeClass
      other: Alias

  class SomeClass:
      ...

--
Ivan
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-dev/attachments/20171102/b1860be3/attachment.html>


More information about the Python-Dev mailing list