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

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.

Leave a Comment