NameError: Forward Reference in Type Hint

NameError: name 'MyClass' is not defined

Quick Answer

You are using a type hint that references a class not yet defined. Use string literals or add 'from __future__ import annotations'.

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

The Fix

from __future__ import annotations

class TreeNode:
    def __init__(self, children: list[TreeNode]):
        self.children = children

Step-by-Step Fix

  1. 1

    Add future annotations

    Add 'from __future__ import annotations' at file top.

  2. 2

    Use string literals

    Write 'list[TreeNode]' as a string.

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