Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Referencing this custom class with typing

I want to define a Node for a Linked List, using type hints. An instance of Node needs a reference to another instance of Node, so I want to accept an optional parameter of type Node in my __init__.

I tried this:

from typing import Optional

class Node:
    def __init__(self, value: int, next: Optional[Node] = None):
        pass

I get an error: Node is not defined from Optional[Node].

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Check out How do I type hint a method with the type of the enclosing class?. You can either:

  1. Use from __future__ import annotations at the top of the file and then use Node as you did.
  2. Use a string ('Node'), see @Diptangsu Goswami’s comment.
  3. From Python 3.11 and onwards (not out yet) you will be able to use from typing import Self and then Optional[Self].
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading