Skip to content

Add cross-language method suggestions to AttributeError messages #146239

@mvanhorn

Description

@mvanhorn

Proposal:

Python's error suggestion system uses Levenshtein distance to suggest similar names on AttributeError, which works well for typos but misses cross-language method confusion - when developers use method names from JavaScript, Java, C#, or Ruby that don't exist in Python.

Today:

>>> items = [1, 2, 3]
>>> items.push(4)
AttributeError: 'list' object has no attribute 'push'

No suggestion is given because push and append are too different for Levenshtein distance to match.

With this change:

>>> items.push(4)
AttributeError: 'list' object has no attribute 'push'. Did you mean: 'append'?

The proposal adds a static translation table of common method names from other languages mapped to their Python equivalents. This runs as a fallback after the existing Levenshtein-based suggestion, so typo suggestions always take priority.

Examples of mappings:

What user writes Current message With this change
list.push(4) no suggestion Did you mean: 'append'?
str.toUpperCase() no suggestion Did you mean: 'upper'?
str.trim() no suggestion Did you mean: 'strip'?
dict.keySet() no suggestion Did you mean: 'keys'?
str.indexOf('x') no suggestion Did you mean: 'index'?

The table covers common methods from JavaScript, Java, C#, and Ruby mapped to Python builtins (list, str, dict). Only exact builtin type matches are checked to avoid false positives on custom classes.

The implementation adds the lookup as a fallback in _compute_suggestion_error() in Lib/traceback.py, after the existing Levenshtein search and nested attribute check. The suggestion path only runs when an error already occurred, so there is no performance impact on normal execution.

The existing _compute_suggestion_error function in Lib/traceback.py (line ~1718) already handles AttributeError, NameError, ImportError, and ModuleNotFoundError with Levenshtein-based matching. This proposal extends the AttributeError path with a static table fallback when Levenshtein finds no match.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    stdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions