Reputation: 11
I have a class Coordinate, which holds 2 integer values, x and y.
I have a method to compare 2 Coordinates to see if they are equal, but I get a NameError when I attempt to define the parameter of this function as a Coordinate.
Here is my code:
def equals(self, other:Coordinate):
try:
return (self.x==other.getX()) and (self.y==other.getY())
except AttributeError:
return False
However, when I run the class file, I get the error
NameError: name 'Coordinate' is not defined
for the first line.
The program works when I remove ":Coordinate" from the parameter but I would like to know if there is a way for it to work while still keeping it there.
Upvotes: 1
Views: 52
Reputation: 387557
First of all, the type hints introduced in PEP 484 do not have any runtime effect. So just because you do other: Coordinate
that does not give you type validation for that function. You would still have to check that yourself or just expect it to be of that type (according to the EAFP principle).
That being said, while type annotations are not evaluated for type safety, they are still an actual meta data syntax which is part of Python. So everything you do there must be completely valid.
In your case, the name Coordinate
is not defined. This basically just means that there is no variable Coordinate
which value can be assigned to that argument’s annotation meta data.
So if Coordinate
is a different type than the one you are defining, then you likely just missed an import from somewhere.
Otherwise, if you are definining Coordinate
right now, then you obviously cannot reference it directly since it does not exist yet. In this case, you will have to use a forward reference:
When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.
So you just use a string 'Coordinate'
here.
Upvotes: 2