Using the class as a type hint for arguments in its methods [duplicate]

The code I have included below throws the following error:

NameError: name 'Vector2' is not defined 

at this line:

def Translate (self, pos: Vector2):

Why does Python not recognize my Vector2 class in the Translate method?

class Vector2:

    def __init__(self, x: float, y: float):

        self.x = x
        self.y = y

    def Translate(self, pos: Vector2):

        self.x += pos.x
        self.y += pos.y

Solution 1:

Because when it encounters Translate (while compiling the class body), Vector2 hasn't been defined yet (it is currently compiling, name binding hasn't been performed); Python naturally complains.

Since this is such a common scenario (type-hinting a class in the body of that class), you should use a forward reference to it by enclosing it in quotes:

class Vector2:    
    # __init__ as defined

    def Translate(self, pos: 'Vector2'):    
        self.x += pos.x
        self.y += pos.y

Python (and any checkers complying to PEP 484) will understand your hint and register it appropriately. Python does recognize this when __annotations__ are accessed through typing.get_type_hints:

from typing import get_type_hints

get_type_hints(Vector2(1,2).Translate)
{'pos': __main__.Vector2}

This has been changed as of Python 3.7; see abarnert's answer below.

Solution 2:

The feature you're asking for is called forward (type) references, and it has been added to Python as of 3.7 (in PEP 563).1 So this is now valid:

from __future__ import annotations
class C:
    def spam(self, other: C) -> C:
        pass

Notice the __future__ statement. This will be necessary until 4.0.

Unfortunately, in Python 3.6 and earlier, this feature is not available, so you have to use string annotations, as explained in Jim Fasarakis Hilliard's answer.

Mypy already supports forward declarations, even when run under Python 3.6—but it doesn't do you much good if the static type checker says your code is fine but the interpreter raises a NameError when you try to actually run it.


1. This was already discussed as a possible feature in PEP 484, but deferred until later, after people had more experience using forward declarations in annotations. PEP 563/Python 3.7 is that "later".