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
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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.
Method 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”.
Method 3
Maybe another alternative is to define the class previously, with an empty implementation. I guess the most common solution is forward reference but my suggestion is more type-safe, which is after all the purpose of adding types.
class Vector2:
pass
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
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0