filter imported names during completion

This commit is contained in:
wutingjia
2024-10-16 11:19:37 +08:00
parent 0f699c6cb6
commit cbf6f8fc7d
2 changed files with 34 additions and 5 deletions

View File

@@ -71,7 +71,7 @@ def filter_names(inference_state, completion_names, stack, like_name, fuzzy, imp
like_name = like_name.lower() like_name = like_name.lower()
for name in completion_names: for name in completion_names:
string = name.string_name string = name.string_name
if string in imported_names: if string in imported_names and string != like_name:
continue continue
if settings.case_insensitive_completion: if settings.case_insensitive_completion:
string = string.lower() string = string.lower()
@@ -177,10 +177,8 @@ class Completion:
cached_name, completion_names = self._complete_python(leaf) cached_name, completion_names = self._complete_python(leaf)
imported_names = [] imported_names = []
if leaf.parent is not None and leaf.parent.type == 'import_as_names': if leaf.parent is not None and leaf.parent.type in ['import_as_names', 'dotted_as_names']:
for child in leaf.parent.children: imported_names.extend(extract_imported_names(leaf.parent))
if child.type == 'name':
imported_names.append(child.value)
completions = list(filter_names(self._inference_state, completion_names, completions = list(filter_names(self._inference_state, completion_names,
self.stack, self._like_name, self.stack, self._like_name,
@@ -678,3 +676,16 @@ def search_in_module(inference_state, module_context, names, wanted_names,
def_ = classes.Name(inference_state, n2) def_ = classes.Name(inference_state, n2)
if not wanted_type or wanted_type == def_.type: if not wanted_type or wanted_type == def_.type:
yield def_ yield def_
def extract_imported_names(node):
imported_names = []
if node.type in ['import_as_names', 'dotted_as_names', 'import_as_name']:
for child in node.children:
if child.type == 'name':
imported_names.append(child.value)
elif child.type == 'import_as_name':
imported_names.extend(extract_imported_names(child))
return imported_names

View File

@@ -307,6 +307,24 @@ def test_os_issues(Script):
assert 'path' in import_names(s, column=len(s) - 3) assert 'path' in import_names(s, column=len(s) - 3)
def test_duplicated_import(Script):
def import_names(*args, **kwargs):
return [d.name for d in Script(*args).complete(**kwargs)]
s = 'import os, o'
assert 'os' not in import_names(s)
assert 'os' in import_names(s, column=len(s) - 3)
s = 'from os import path, p'
assert 'path' not in import_names(s)
assert 'path' in import_names(s, column=len(s) - 3)
s = 'import path as pp, p'
assert 'path' not in import_names(s)
s = 'from os import path as pp, p'
assert 'path' not in import_names(s)
def test_path_issues(Script): def test_path_issues(Script):
""" """
See pull request #684 for details. See pull request #684 for details.