@@ -1187,12 +1187,20 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,
11871187 elif exc_type and issubclass (exc_type , AttributeError ) and \
11881188 getattr (exc_value , "name" , None ) is not None :
11891189 wrong_name = getattr (exc_value , "name" , None )
1190- suggestion = _compute_suggestion_error (exc_value , exc_traceback , wrong_name )
1191- if suggestion :
1192- if suggestion .isascii ():
1193- self ._str += f". Did you mean '.{ suggestion } ' instead of '.{ wrong_name } '?"
1194- else :
1195- self ._str += f". Did you mean '.{ suggestion } ' ({ suggestion !a} ) instead of '.{ wrong_name } ' ({ wrong_name !a} )?"
1190+ # Check cross-language/wrong-type hints first (more specific),
1191+ # then fall back to Levenshtein distance suggestions.
1192+ hint = None
1193+ if hasattr (exc_value , 'obj' ):
1194+ hint = _get_cross_language_hint (exc_value .obj , wrong_name )
1195+ if hint :
1196+ self ._str += f". { hint } "
1197+ else :
1198+ suggestion = _compute_suggestion_error (exc_value , exc_traceback , wrong_name )
1199+ if suggestion :
1200+ if suggestion .isascii ():
1201+ self ._str += f". Did you mean '.{ suggestion } ' instead of '.{ wrong_name } '?"
1202+ else :
1203+ self ._str += f". Did you mean '.{ suggestion } ' ({ suggestion !a} ) instead of '.{ wrong_name } ' ({ wrong_name !a} )?"
11961204 elif exc_type and issubclass (exc_type , NameError ) and \
11971205 getattr (exc_value , "name" , None ) is not None :
11981206 wrong_name = getattr (exc_value , "name" , None )
@@ -1689,6 +1697,62 @@ def print(self, *, file=None, chain=True, **kwargs):
16891697_MOVE_COST = 2
16901698_CASE_COST = 1
16911699
1700+ # Cross-language method suggestions for builtin types.
1701+ # Consulted as a fallback when Levenshtein-based suggestions find no match.
1702+ #
1703+ # Inclusion criteria:
1704+ #
1705+ # 1. Must have evidence of real cross-language confusion (Stack Overflow
1706+ # traffic, bug reports in production repos, developer survey data).
1707+ # 2. Must not be catchable by Levenshtein distance (too different from
1708+ # the correct Python method name).
1709+ #
1710+ # Each entry maps a wrong method name to a list of (type, suggestion, is_raw)
1711+ # tuples. The lookup checks isinstance() so subclasses are also matched.
1712+ # If is_raw is False, the suggestion is wrapped in "Did you mean '.X'?".
1713+ # If is_raw is True, the suggestion is rendered as-is.
1714+ #
1715+ # See https://github.com/python/cpython/issues/146406.
1716+ _CROSS_LANGUAGE_HINTS = frozendict ({
1717+ # list -- JavaScript/Ruby equivalents
1718+ "push" : ((list , "append" , False ),),
1719+ "concat" : ((list , "extend" , False ),),
1720+ # list -- Java/C# equivalents
1721+ "addAll" : ((list , "extend" , False ),),
1722+ "contains" : ((list , "Use 'x in list'." , True ),),
1723+ # list -- wrong-type suggestion (user expected a set)
1724+ "add" : ((list , "Did you mean to use a 'set' object?" , True ),
1725+ (frozenset , "Did you mean to use a 'set' object?" , True )),
1726+ # str -- JavaScript equivalents
1727+ "toUpperCase" : ((str , "upper" , False ),),
1728+ "toLowerCase" : ((str , "lower" , False ),),
1729+ "trimStart" : ((str , "lstrip" , False ),),
1730+ "trimEnd" : ((str , "rstrip" , False ),),
1731+ # dict -- Java/JavaScript equivalents
1732+ "keySet" : ((dict , "keys" , False ),),
1733+ "entrySet" : ((dict , "items" , False ),),
1734+ "entries" : ((dict , "items" , False ),),
1735+ "putAll" : ((dict , "update" , False ),),
1736+ "put" : ((dict , "Use d[k] = v." , True ),),
1737+ # tuple -- mutable method on immutable type (user expected a list)
1738+ "append" : ((tuple , "Did you mean to use a 'list' object?" , True ),),
1739+ "extend" : ((tuple , "Did you mean to use a 'list' object?" , True ),),
1740+ "insert" : ((tuple , "Did you mean to use a 'list' object?" , True ),),
1741+ "remove" : ((tuple , "Did you mean to use a 'list' object?" , True ),
1742+ (frozenset , "Did you mean to use a 'set' object?" , True )),
1743+ # frozenset -- mutable method on immutable type (user expected a set)
1744+ "discard" : ((frozenset , "Did you mean to use a 'set' object?" , True ),),
1745+ # frozendict -- mutable method on immutable type (user expected a dict)
1746+ "update" : ((frozenset , "Did you mean to use a 'set' object?" , True ),
1747+ (frozendict , "Did you mean to use a 'dict' object?" , True )),
1748+ # float -- bitwise operators belong to int
1749+ "__or__" : ((float , "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'." , True ),),
1750+ "__and__" : ((float , "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'." , True ),),
1751+ "__xor__" : ((float , "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'." , True ),),
1752+ "__lshift__" : ((float , "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'." , True ),),
1753+ "__rshift__" : ((float , "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'." , True ),),
1754+ })
1755+
16921756
16931757def _substitution_cost (ch_a , ch_b ):
16941758 if ch_a == ch_b :
@@ -1751,6 +1815,24 @@ def _check_for_nested_attribute(obj, wrong_name, attrs):
17511815 return None
17521816
17531817
1818+ def _get_cross_language_hint (obj , wrong_name ):
1819+ """Check if wrong_name is a common method name from another language,
1820+ a mutable method on an immutable type, or a method tried on None.
1821+
1822+ Uses isinstance() so subclasses of builtin types also get hints.
1823+ Returns a formatted hint string, or None.
1824+ """
1825+ entries = _CROSS_LANGUAGE_HINTS .get (wrong_name )
1826+ if entries is None :
1827+ return None
1828+ for check_type , hint , is_raw in entries :
1829+ if isinstance (obj , check_type ):
1830+ if is_raw :
1831+ return hint
1832+ return f"Did you mean '.{ hint } '?"
1833+ return None
1834+
1835+
17541836def _get_safe___dir__ (obj ):
17551837 # Use obj.__dir__() to avoid a TypeError when calling dir(obj).
17561838 # See gh-131001 and gh-139933.
0 commit comments