Python interpreter: improve suggestions for possible mappings (#266)

This commit is contained in:
Aymeric Roucher 2025-01-20 11:40:43 +01:00 committed by GitHub
parent d19ebc7a48
commit 3c18d4d588
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 15 additions and 5 deletions

View File

@ -641,11 +641,13 @@ def evaluate_subscript(
return value[index]
elif index in value:
return value[index]
elif isinstance(index, str) and isinstance(value, Mapping):
else:
error_message = f"Could not index {value} with '{index}'."
if isinstance(index, str) and isinstance(value, Mapping):
close_matches = difflib.get_close_matches(index, list(value.keys()))
if len(close_matches) > 0:
return value[close_matches[0]]
raise InterpreterError(f"Could not index {value} with '{index}'.")
error_message += f" Maybe you meant one of these indexes instead: {str(close_matches)}"
raise InterpreterError(error_message)
def evaluate_name(

View File

@ -897,3 +897,11 @@ shift_intervals
code = "import doctest;doctest.inspect.os.system('echo bad command passed')"
with pytest.raises(AttributeError):
evaluate_python_code(code, authorized_imports=["doctest"])
def test_close_matches_subscript(self):
code = 'capitals = {"Czech Republic": "Prague", "Monaco": "Monaco", "Bhutan": "Thimphu"};capitals["Butan"]'
with pytest.raises(Exception) as e:
evaluate_python_code(code)
assert "Maybe you meant one of these indexes instead" in str(
e
) and "['Bhutan']" in str(e).replace("\\", "")