Skip to content

Commit dd03085

Browse files
authored
Fix inline comments that include text with import (#639)
1 parent c8e4e99 commit dd03085

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

pylsp/plugins/symbols.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
# Copyright 2021- Python Language Server Contributors.
33

44
import logging
5+
import re
56
from pathlib import Path
67

78
from pylsp import hookimpl
@@ -19,6 +20,9 @@ def pylsp_document_symbols(config, document):
1920
symbols = []
2021
exclude = set({})
2122
redefinitions = {}
23+
pattern_import = re.compile(
24+
r"^\s*(?!#)\s*(from\s+[.\w]+(\.[\w]+)*\s+import\s+[\w\s,()*]+|import\s+[\w\s,.*]+)"
25+
)
2226

2327
while definitions != []:
2428
d = definitions.pop(0)
@@ -27,7 +31,8 @@ def pylsp_document_symbols(config, document):
2731
if not add_import_symbols:
2832
# Skip if there's an import in the code the symbol is defined.
2933
code = d.get_line_code()
30-
if " import " in code or "import " in code:
34+
35+
if pattern_import.match(code):
3136
continue
3237

3338
# Skip imported symbols comparing module names.

test/plugins/test_symbols.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,17 @@ def main(x):
3030
3131
"""
3232

33+
DOC_IMPORTS = """from . import something
34+
from ..module import something
35+
from module import (a, b)
36+
37+
def main():
38+
# import ignored
39+
print("from module import x") # string with import
40+
return something
41+
42+
"""
43+
3344

3445
def helper_check_symbols_all_scope(symbols):
3546
# All eight symbols (import sys, a, B, __init__, x, y, main, y)
@@ -73,6 +84,24 @@ def sym(name):
7384
assert sym("main")["location"]["range"]["end"] == {"line": 12, "character": 0}
7485

7586

87+
def test_symbols_complex_imports(config, workspace):
88+
doc = Document(DOC_URI, workspace, DOC_IMPORTS)
89+
config.update({"plugins": {"jedi_symbols": {"all_scopes": False}}})
90+
symbols = pylsp_document_symbols(config, doc)
91+
92+
import_symbols = [s for s in symbols if s["kind"] == SymbolKind.Module]
93+
94+
assert len(import_symbols) == 4
95+
96+
names = [s["name"] for s in import_symbols]
97+
assert "something" in names
98+
assert "a" in names or "b" in names
99+
100+
assert any(
101+
s["name"] == "main" and s["kind"] == SymbolKind.Function for s in symbols
102+
)
103+
104+
76105
def test_symbols_all_scopes(config, workspace) -> None:
77106
doc = Document(DOC_URI, workspace, DOC)
78107
symbols = pylsp_document_symbols(config, doc)

0 commit comments

Comments
 (0)