Gaze
Gaze

Reputation: 420

Getting python NameError: name XY is not defined despite passing mypy typechecking

I'm trying to write a generic class that has methods that take an argument of the class itself, as well as storing a pointer to a next instance of itself. I pass mypy (and feel my code should work), but running it with the python interpreter gives me

NameError: name 'MyTestClass' is not defined

Minimum Code example: (file mydatastructure/mydatastructure.py)

from typing import Generic, TypeVar

T = TypeVar("T")


class MyTestClass(Generic[T]):
    def __init__(self, val: T) -> None:
        self.val = val

    def self_referential_method(self, other: MyTestClass[T]) -> bool:
        return self.val == other.val


if __name__ == "__main__":
    print("Hello")
    a = MyTestClass[int](3)
    b = MyTestClass[int](2)
    print(a.self_referential_method(b))

Typechecking passes:

mypy mydatastructure/
Success: no issues found in 2 source files

Executing the code does not:

python mydatastructure/mydatastructure.py 
Traceback (most recent call last):
  File "/home/jan/toy_projects/DataStructuresAndAlgorithms/python/mydatastructure/mydatastructure.py", line 7, in <module>
    class MyTestClass(Generic[T]):
  File "/home/jan/toy_projects/DataStructuresAndAlgorithms/python/mydatastructure/mydatastructure.py", line 11, in MyTestClass
    def self_referential_method(self, other: MyTestClass[T]) -> bool:
NameError: name 'MyTestClass' is not defined

In addition, I would like the following to work:

class MyTestClass(Generic[T]):
    def __init__(self, val: T, next: Optional[MyTestClass[T]]) -> None:
        self.val = val
        self.next : Optional[MyTestClass[T]] = next

    def self_referential_method(self, other: MyTestClass[T]) -> bool:
        return self.val == other.val

Upvotes: 0

Views: 91

Answers (1)

Paweł Rubin
Paweł Rubin

Reputation: 3439

Add from __future__ import annotations import.

Upvotes: 1

Related Questions