[Python-ideas] Delay evaluation of annotations

Chris Angelico rosuav at gmail.com
Thu Sep 22 17:17:27 EDT 2016


On Fri, Sep 23, 2016 at 6:48 AM, Alexander Belopolsky
<alexander.belopolsky at gmail.com> wrote:
> On the third thought, this entire feature can be implemented in the
> metaclass by injecting A = 'A' in the dict in __prepare__.

That would be the easiest, and least magical, solution. It simply
means that the name of the current class is available as a
pseudo-reference to itself, for typing purposes only. It parallels
function recursion, which is done using the function's name:

# Recursion in functions
def spam():
    return spam()

# Recursion in type annotations
class Spam:
    def make_spam() -> Spam:
        return self

Clean and simple. And there's less magic here than super() - a lot less.

It does mean that Spam.Spam == "Spam" forever afterwards, but I doubt
that's going to break anything. It'd be just like __name__, except
that currently, Spam.__name__ is set afterwards, so it's not available
during class definition (and the module's name will be used instead).

ChrisA


More information about the Python-ideas mailing list