Python: Method in class that returns instance of itself throwing NameError

Date: 2019-10-07 | python | name-error | troubleshoot | typing | annotations |

problem

I'm trying to create a method in a class that returns a new instance of itself however I keep getting NameError: name 'CLASSNAME' is not defined. This only happens when I add the type annotation that the method returns and instance of itself. If I don't do this, then I don't get the compiler error and the function works as expected. Obviously it's better to have the correct type on the function, so how can I annotate the function to return the same class?

solution

This issue is resolved natively in Python 4.0+ but in previous versions, you'll have to import annotations from __future__ like from __future__ import annotations.

Here's an example that works without the annotation, breaks with the annotation, and is then fixed with the annotation so long as you import annotations:

from __future__ import annotations

class Point:
    x: float
    y: float

    def __init__(self, x=0.0, y=0.0):
        self.x = x
        self.y = y

    def clone(self) -> Point:
        return Point(self.x, self.y)

point = Point(1, 1)
cloned_point = point.clone()

print(cloned_point)

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I've built by subscribing here.

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.