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

Published: 2019-10-07 17:08:34 -0400 -0400

Reading time: 2 mins (200 words)

Tags: 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.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus