1

I have a linked list that I have implemented in Java that I want to implement in Python. I've got my constructor for the node as followed:

public class Node<T> {

  private T data; 
  private Node<T> next; 

  public Node(T data, Node<T> next) { #Param next is of type Node<T>. Can I do this in Python?
    this.data = data;
    this.next = next;
  }

Is there a way I can implement this in Python with the 'typing' module? I know that it doesn't enforce the typing on runtime, but I'm just wondering if it is possible.

I've tried this:

from typing import TypeVar, Generic

T = TypeVar('T') #Any generic type

class Node(Generic[T]):
    
    def __init__(self, data : T, next : Node[T]): #Node[T] raises NameError error thrown
        self.data = data #Type T
        self.next = next #Type Node[T]

But the "Node[T]" in the param next is what is raising a NameError. When I remove 'Node[T]' it will work, but I would like to find a way to hint the type of the next param.

NameError: name 'Node' is not defined

Even though the typing is not enforced, is it possible to write out that the parameter is of type Node[T]? I've tried replacing with 'Node(T), Node, self, etc.

dftag
  • 85
  • 2
  • 8

0 Answers0