["python"]
type hinting within a class

class Node: def append_child(self, node: Node): if node != None: self.first_child = node self.child_nodes += [node] How do I do node: Node? Because when I run it, it says name 'Node' is not defined. Should I just remove the : Node and instance check it inside the function? But then how could I access node's properties (which I would expect to be instance of Node class)? I don't know how implement type casting in Python, BTW.
"self" references in type checking are typically done using strings: class Node: def append_child(self, node: 'Node'): if node != None: self.first_child = node self.child_nodes += [node] This is described in the "Forward references" section of PEP-0484. Please note that this doesn't do any type-checking or casting. This is a type hint which python (normally) disregards completely1. However, third party tools (e.g. mypy), use type hints to do static analysis on your code and can generate errors before runtime. Also, starting with python3.7, you can implicitly convert all of your type-hints to strings within a module by using the from __future__ import annotations (and in python4.0, this will be the default). 1The hints are introspectable -- So you could use them to build some kind of runtime checker using decorators or the like if you really wanted to, but python doesn't do this by default.