Why This Happens
Type hints are evaluated at definition time by default. If a class references itself in a type hint, Python raises NameError. String literals or future annotations defer evaluation.
The Problem
class TreeNode:
def __init__(self, children: list[TreeNode]):
self.children = childrenThe Fix
from __future__ import annotations
class TreeNode:
def __init__(self, children: list[TreeNode]):
self.children = childrenStep-by-Step Fix
- 1
Add future annotations
Add 'from __future__ import annotations' at file top.
- 2
Use string literals
Write 'list[TreeNode]' as a string.
- 3
Use TYPE_CHECKING
Import under 'if TYPE_CHECKING:' for type-only imports.
Bugsly catches this automatically
Bugsly's AI analyzes this error pattern in real-time, explains what went wrong in plain English, and suggests the exact fix — before your users even report it.
Try Bugsly free