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

Python function annotation: class is not defined in method

I am trying to define a python function annotation for the method of a class. The method returns a list whose elements are objects of the class. How can I do this?

Example,

class Node:
  def __init__(self):
    self.children = []

  def get_children(self) -> list[Node]:
    return self.children    

Error message:

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

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_18676/2160074272.py in <module>
----> 1 class Node:
      2     def __init__(self):
      3         self.children = []
      4 
      5     def get_children(self) -> list[Node]:

~\AppData\Local\Temp/ipykernel_18676/2160074272.py in Node()
      3         self.children = []
      4 
----> 5     def get_children(self) -> list[Node]:
      6         return self.children

NameError: name 'Node' is not defined

>Solution :

Putting the class name in quotations is a perfectly viable solution, but I’d like to point out a more future-friendly one.

There’s a future import on the table that will effectively automatically wrap all type annotations in quotes, to avoid this exact problem. As of Python 3.10, it’ll be the default, so it’s recommended to go ahead and start using it now.

from __future__ import annotations

class Node:
  def __init__(self):
    self.children = []

  def get_children(self) -> list[Node]:
    return self.children
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