Home > OS >  Python function annotation: class is not defined in method
Python function annotation: class is not defined in method

Time:11-12

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:

---------------------------------------------------------------------------
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

CodePudding user response:

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

CodePudding user response:

Per @Tomasito665's comment, the solution to this is putting the class in quotations ("class_name"):

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

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