-
-
Notifications
You must be signed in to change notification settings - Fork 34.3k
gh-146406: Add cross-language method suggestions for builtin AttributeError #146407
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mvanhorn
wants to merge
6
commits into
python:main
Choose a base branch
from
mvanhorn:osc/cross-language-attr-hints
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+163
−0
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7adad8b
Add cross-language method suggestions for builtin AttributeError
mvanhorn aecaacb
fix NEWS entry filename for bedevere bot
mvanhorn 6d58cdc
Address review feedback from @nedbat and @ZeroIntensity
mvanhorn 8a39e32
Add What's New entry for cross-language AttributeError hints
mvanhorn 196dbe4
Address review feedback from @picnixz
mvanhorn 99e106a
Keep Levenshtein criterion, remove survey restriction per picnixz
mvanhorn File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -1153,6 +1153,10 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None, | |||||
| self._str += f". Did you mean '.{suggestion}' instead of '.{wrong_name}'?" | ||||||
| else: | ||||||
| self._str += f". Did you mean '.{suggestion}' ({suggestion!a}) instead of '.{wrong_name}' ({wrong_name!a})?" | ||||||
| elif hasattr(exc_value, 'obj'): | ||||||
| hint = _get_cross_language_hint(exc_value.obj, wrong_name) | ||||||
| if hint: | ||||||
| self._str += f". {hint}" | ||||||
| elif exc_type and issubclass(exc_type, NameError) and \ | ||||||
| getattr(exc_value, "name", None) is not None: | ||||||
| wrong_name = getattr(exc_value, "name", None) | ||||||
|
|
@@ -1649,6 +1653,42 @@ def print(self, *, file=None, chain=True, **kwargs): | |||||
| _MOVE_COST = 2 | ||||||
| _CASE_COST = 1 | ||||||
|
|
||||||
| # Cross-language method suggestions for builtin types. | ||||||
| # Consulted as a fallback when Levenshtein-based suggestions find no match. | ||||||
| # | ||||||
| # Inclusion criteria: | ||||||
| # 1. Must have evidence of real cross-language confusion (Stack Overflow | ||||||
| # traffic, bug reports in production repos, developer survey data). | ||||||
| # 2. Must not be catchable by Levenshtein distance (too different from | ||||||
| # the correct Python method name). | ||||||
| # | ||||||
| # Each entry maps (builtin_type, wrong_name) to a (suggestion, is_raw) tuple. | ||||||
| # If is_raw is False, the suggestion is wrapped in "Did you mean '.X'?". | ||||||
| # If is_raw is True, the suggestion is rendered as-is. | ||||||
| # | ||||||
| # See https://github.com/python/cpython/issues/146406. | ||||||
| _CROSS_LANGUAGE_HINTS = { | ||||||
| # list -- JavaScript/Ruby equivalents | ||||||
| (list, "push"): ("append", False), | ||||||
| (list, "concat"): ("extend", False), | ||||||
| # list -- Java/C# equivalents | ||||||
| (list, "addAll"): ("extend", False), | ||||||
| (list, "contains"): ("Use 'x in list' to check membership.", True), | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Hum, maybe make it shorter:
Suggested change
|
||||||
| # list -- wrong-type suggestion more likely means the user expected a set | ||||||
| (list, "add"): ("Did you mean to use a 'set' object?", True), | ||||||
| # str -- JavaScript equivalents | ||||||
| (str, "toUpperCase"): ("upper", False), | ||||||
| (str, "toLowerCase"): ("lower", False), | ||||||
| (str, "trimStart"): ("lstrip", False), | ||||||
| (str, "trimEnd"): ("rstrip", False), | ||||||
| # dict -- Java/JavaScript equivalents | ||||||
| (dict, "keySet"): ("keys", False), | ||||||
| (dict, "entrySet"): ("items", False), | ||||||
| (dict, "entries"): ("items", False), | ||||||
| (dict, "putAll"): ("update", False), | ||||||
| (dict, "put"): ("Use d[k] = v for item assignment.", True), | ||||||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same suggestion here:
Suggested change
|
||||||
| } | ||||||
|
|
||||||
|
|
||||||
| def _substitution_cost(ch_a, ch_b): | ||||||
| if ch_a == ch_b: | ||||||
|
|
@@ -1711,6 +1751,22 @@ def _check_for_nested_attribute(obj, wrong_name, attrs): | |||||
| return None | ||||||
|
|
||||||
|
|
||||||
| def _get_cross_language_hint(obj, wrong_name): | ||||||
| """Check if wrong_name is a common method name from another language. | ||||||
| Only checks exact builtin types (list, str, dict) to avoid false | ||||||
| positives on subclasses that may intentionally lack these methods. | ||||||
| Returns a formatted hint string, or None. | ||||||
| """ | ||||||
| entry = _CROSS_LANGUAGE_HINTS.get((type(obj), wrong_name)) | ||||||
| if entry is None: | ||||||
| return None | ||||||
| hint, is_raw = entry | ||||||
| if is_raw: | ||||||
| return hint | ||||||
| return f"Did you mean '.{hint}'?" | ||||||
|
|
||||||
|
|
||||||
| def _get_safe___dir__(obj): | ||||||
| # Use obj.__dir__() to avoid a TypeError when calling dir(obj). | ||||||
| # See gh-131001 and gh-139933. | ||||||
|
|
||||||
4 changes: 4 additions & 0 deletions
4
Misc/NEWS.d/next/Library/2026-03-25-07-17-41.gh-issue-146406.ydsmqe.rst
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,4 @@ | ||
| Cross-language method suggestions are now shown for :exc:`AttributeError` on | ||
| builtin types when the existing Levenshtein-based suggestions find no match. | ||
| For example, ``[].push()`` now suggests ``append`` and | ||
| ``"".toUpperCase()`` suggests ``upper``. |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hum, it's kind of verbose to have one test per method. What about having a single test_cross_language() which runs all these tests?