[Python-ideas] PEP 563 and expensive backwards compatibility

Lukasz Langa lukasz at langa.pl
Wed Sep 13 19:43:58 EDT 2017


> On Sep 13, 2017, at 6:37 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> 
> I think it would be useful for the PEP to include a definition of an
> "eager annotations" decorator that did something like:
> 
>    def eager_annotations(f):
>        ns = f.__globals__
>        annotations = f.__annotations__
>        for k, v in annotations.items():
>            annotations[k] = eval(v, ns)
>        return f
> 
> And pointed out that you can create variants of that which also pass
> in the locals() namespace (or use sys._getframes() to access it
> dynamically).
> 
> That way, during the "from __future__ import lazy_annotations" period,
> folks will have clearer guidance on how to explicitly opt-in to eager
> evaluation via function and class decorators.

I like this idea! For classes it would have to be a function that you call post factum. The way class decorators are implemented, they cannot evaluate annotations that contain forward references. For example:

class Tree:
    left: Tree
    right: Tree

    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This is true today, get_type_hints() called from within a class decorator will fail on this class. However, a function performing postponed evaluation can do this without issue. If a class decorator knew what name a class is about to get, that would help. But that's a different PEP and I'm not writing that one ;-)

- Ł
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 842 bytes
Desc: Message signed with OpenPGP
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20170913/6689763c/attachment.sig>


More information about the Python-ideas mailing list