You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I have a class called Node which represents a general node for a linked list. As defined, a node has two attributes: the node's data and a memory reference to the following node.
When I run this module with the mypy checker (mypy node.py), it has no issue with this. However, python3 node.py yields the following error: NameError: name 'Node' is not defined.
I tried changing next: Node[T] to next: object, but that generated a mypy error (error: Incompatible types in assignment (expression has type "object", variable has type Node[Any])).
How do I reconcile the differences in behavior when running this module with python3 and mypy while also maintaining the structure of this class?
The text was updated successfully, but these errors were encountered:
What's happening here is that when the Python interpreter hits the __init__ method, the Node class is still in the process of being defined, and so Node hasn't been bound to the environment yet. This explains why Python claims Node[T] isn't defined.
The workaround is to use forward references and write Node[T] as a string, which mypy will also understand:
This will make your code work nicely with both mypy and Python.
That said, it would probably be a good idea for mypy to report an error in cases like this, since it seems to be a common tripup. I found a pre-existing issue for it here, but it doesn't seem like anybody has started working on this yet.
I have a class called
Node
which represents a general node for a linked list. As defined, a node has two attributes: the node's data and a memory reference to the following node.When I run this module with the mypy checker (
mypy node.py
), it has no issue with this. However,python3 node.py
yields the following error:NameError: name 'Node' is not defined
.I tried changing
next: Node[T]
tonext: object
, but that generated a mypy error (error: Incompatible types in assignment (expression has type "object", variable has type Node[Any])
).How do I reconcile the differences in behavior when running this module with
python3
andmypy
while also maintaining the structure of this class?The text was updated successfully, but these errors were encountered: