Skip to content

Commit 0fabb7d

Browse files
jwortmannpredragnikolicrchldeathaxerwols
authored
Use variable annotations instead of type comments on Python 3.8 (#2450)
* "Add .python-version file" * remove pathlib from dependencies * change import * Revert "change import" (: This reverts commit c70cd57. * Fix failing unittests on MacOS (#2436) This commit adopts `unittesting.ViewTestCase` to run view related test cases. ViewTestCase ... 1. provides `view` and `window` members pointing to a dedicated view, being created for testing. 2. ensures not to close empty windows, which was probably the most likely reason for unittests failing before on MacOS. * keep the same order as before * rchlint * add release notes * tweak release message * Be more descriptive of what the user expect, or what the user can do if things go wrong * tweak words * Use variable annotations instead of type comments --------- Co-authored-by: Предраг Николић <[email protected]> Co-authored-by: Rafal Chlodnicki <[email protected]> Co-authored-by: deathaxe <[email protected]> Co-authored-by: Raoul Wols <[email protected]>
1 parent 4b02dbd commit 0fabb7d

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+363
-364
lines changed

boot.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def _get_final_subclasses(derived: List[Type], results: List[Type]) -> None:
9898

9999

100100
def _register_all_plugins() -> None:
101-
plugin_classes = [] # type: List[Type[AbstractPlugin]]
101+
plugin_classes: List[Type[AbstractPlugin]] = []
102102
_get_final_subclasses(AbstractPlugin.__subclasses__(), plugin_classes)
103103
for plugin_class in plugin_classes:
104104
try:

plugin/code_actions.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -37,10 +37,10 @@ class CodeActionsManager:
3737
"""Manager for per-location caching of code action responses."""
3838

3939
def __init__(self) -> None:
40-
self._response_cache = None # type: Optional[Tuple[str, Promise[List[CodeActionsByConfigName]]]]
41-
self.menu_actions_cache_key = None # type: Optional[str]
42-
self.refactor_actions_cache = [] # type: List[Tuple[str, CodeAction]]
43-
self.source_actions_cache = [] # type: List[Tuple[str, CodeAction]]
40+
self._response_cache: Optional[Tuple[str, Promise[List[CodeActionsByConfigName]]]] = None
41+
self.menu_actions_cache_key: Optional[str] = None
42+
self.refactor_actions_cache: List[Tuple[str, CodeAction]] = []
43+
self.source_actions_cache: List[Tuple[str, CodeAction]] = []
4444

4545
def request_for_region_async(
4646
self,
@@ -74,7 +74,7 @@ def request_for_region_async(
7474
self.source_actions_cache.clear()
7575

7676
def request_factory(sb: SessionBufferProtocol) -> Optional[Request]:
77-
diagnostics = [] # type: List[Diagnostic]
77+
diagnostics: List[Diagnostic] = []
7878
for diag_sb, diags in session_buffer_diagnostics:
7979
if diag_sb == sb:
8080
diagnostics = diags
@@ -122,7 +122,7 @@ def request_factory(sb: SessionBufferProtocol) -> Optional[Request]:
122122
matching_kinds = get_matching_on_save_kinds(on_save_actions, session_kinds)
123123
if not matching_kinds:
124124
return None
125-
diagnostics = [] # type: List[Diagnostic]
125+
diagnostics: List[Diagnostic] = []
126126
for diag_sb, diags in session_buffer_diagnostics:
127127
if diag_sb == sb:
128128
diagnostics = diags
@@ -155,13 +155,13 @@ def on_response(
155155
actions = response_filter(sb, response)
156156
return (sb.session.config.name, actions)
157157

158-
tasks = [] # type: List[Promise[CodeActionsByConfigName]]
158+
tasks: List[Promise[CodeActionsByConfigName]] = []
159159
for sb in listener.session_buffers_async('codeActionProvider'):
160160
session = sb.session
161161
request = request_factory(sb)
162162
if request:
163163
response_handler = partial(on_response, sb)
164-
task = session.send_request_task(request) # type: Promise[Optional[List[CodeActionOrCommand]]]
164+
task: Promise[Optional[List[CodeActionOrCommand]]] = session.send_request_task(request)
165165
tasks.append(task.then(response_handler))
166166
# Return only results for non-empty lists.
167167
return Promise.all(tasks) \
@@ -172,7 +172,7 @@ def on_response(
172172

173173

174174
def get_session_kinds(sb: SessionBufferProtocol) -> List[CodeActionKind]:
175-
session_kinds = sb.get_capability('codeActionProvider.codeActionKinds') # type: Optional[List[CodeActionKind]]
175+
session_kinds: Optional[List[CodeActionKind]] = sb.get_capability('codeActionProvider.codeActionKinds')
176176
return session_kinds or []
177177

178178

@@ -254,7 +254,7 @@ def _handle_response_async(self, responses: List[CodeActionsByConfigName]) -> No
254254
if self._cancelled:
255255
return
256256
view = self._task_runner.view
257-
tasks = [] # type: List[Promise]
257+
tasks: List[Promise] = []
258258
for config_name, code_actions in responses:
259259
session = self._task_runner.session_by_name(config_name, 'codeActionProvider')
260260
if session:
@@ -308,7 +308,7 @@ def _run_async(self, only_kinds: Optional[List[CodeActionKind]] = None) -> None:
308308

309309
def _handle_code_actions(self, response: List[CodeActionsByConfigName], run_first: bool = False) -> None:
310310
# Flatten response to a list of (config_name, code_action) tuples.
311-
actions = [] # type: List[Tuple[ConfigName, CodeActionOrCommand]]
311+
actions: List[Tuple[ConfigName, CodeActionOrCommand]] = []
312312
for config_name, session_actions in response:
313313
actions.extend([(config_name, action) for action in session_actions])
314314
if actions:

plugin/code_lens.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def __init__(self, view: sublime.View) -> None:
108108
self.view = view
109109
self._init = False
110110
self._phantom = sublime.PhantomSet(view, self.CODE_LENS_KEY)
111-
self._code_lenses = {} # type: Dict[Tuple[int, int], List[CodeLensData]]
111+
self._code_lenses: Dict[Tuple[int, int], List[CodeLensData]] = {}
112112

113113
def clear(self) -> None:
114114
self._code_lenses.clear()
@@ -134,10 +134,10 @@ def handle_response(self, session_name: str, response: List[CodeLens]) -> None:
134134
self._init = True
135135
responses = [CodeLensData(data, self.view, session_name) for data in response]
136136
responses.sort(key=lambda c: c.region)
137-
result = {
137+
result: Dict[Tuple[int, int], List[CodeLensData]] = {
138138
region.to_tuple(): list(groups)
139139
for region, groups in itertools.groupby(responses, key=lambda c: c.region)
140-
} # type: Dict[Tuple[int, int], List[CodeLensData]]
140+
}
141141

142142
# Fast path: no extra work to do
143143
if self.is_empty():
@@ -215,7 +215,7 @@ def run(self, edit: sublime.Edit) -> None:
215215
listener = windows.listener_for_view(self.view)
216216
if not listener:
217217
return
218-
code_lenses = [] # type: List[CodeLensExtended]
218+
code_lenses: List[CodeLensExtended] = []
219219
for region in self.view.sel():
220220
for sv in listener.session_views_async():
221221
code_lenses.extend(sv.get_resolved_code_lenses_for_region(region))

plugin/color.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,11 +19,11 @@ def run(self, edit: sublime.Edit, color_information: ColorInformation) -> None:
1919
if session:
2020
self._version = self.view.change_count()
2121
self._range = color_information['range']
22-
params = {
22+
params: ColorPresentationParams = {
2323
'textDocument': text_document_identifier(self.view),
2424
'color': color_information['color'],
2525
'range': self._range
26-
} # type: ColorPresentationParams
26+
}
2727
session.send_request_async(Request.colorPresentation(params, self.view), self._handle_response_async)
2828

2929
def want_event(self) -> bool:
@@ -38,7 +38,7 @@ def _handle_response_async(self, response: List[ColorPresentation]) -> None:
3838
if self._version != self.view.change_count():
3939
return
4040
old_text = self.view.substr(range_to_region(self._range, self.view))
41-
self._filtered_response = [] # type: List[ColorPresentation]
41+
self._filtered_response: List[ColorPresentation] = []
4242
for item in response:
4343
# Filter out items that would apply no change
4444
text_edit = item.get('textEdit')

plugin/completion.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def format_completion(
5656
lsp_detail = (item.get('detail') or "").replace("\n", " ")
5757
completion_kind = item.get('kind')
5858
kind = COMPLETION_KINDS.get(completion_kind, sublime.KIND_AMBIGUOUS) if completion_kind else sublime.KIND_AMBIGUOUS
59-
details = [] # type: List[str]
59+
details: List[str] = []
6060
if can_resolve_completion_items or item.get('documentation'):
6161
# Not using "make_command_link" in a hot path to avoid slow json.dumps.
6262
args = '{{"view_id":{},"command":"lsp_resolve_docs","args":{{"index":{},"session_name":"{}"}}}}'.format(
@@ -132,7 +132,7 @@ def completion_with_defaults(item: CompletionItem, item_defaults: CompletionItem
132132
""" Currently supports defaults for: ["editRange", "insertTextFormat", "data"] """
133133
if not item_defaults:
134134
return item
135-
default_text_edit = None # type: Optional[Union[TextEdit, InsertReplaceEdit]]
135+
default_text_edit: Optional[Union[TextEdit, InsertReplaceEdit]] = None
136136
edit_range = item_defaults.get('editRange')
137137
if edit_range:
138138
# If textEditText is not provided and a list's default range is provided
@@ -182,7 +182,7 @@ def __init__(
182182
self._triggered_manually = triggered_manually
183183
self._on_done_async = on_done_async
184184
self._resolved = False
185-
self._pending_completion_requests = {} # type: Dict[int, weakref.ref[Session]]
185+
self._pending_completion_requests: Dict[int, weakref.ref[Session]] = {}
186186

187187
def query_completions_async(self, sessions: List[Session]) -> None:
188188
promises = [self._create_completion_request_async(session) for session in sessions]
@@ -206,10 +206,10 @@ def _resolve_completions_async(self, responses: List[ResolvedCompletions]) -> No
206206
if self._resolved:
207207
return
208208
LspSelectCompletionCommand.completions = {}
209-
items = [] # type: List[sublime.CompletionItem]
210-
item_defaults = {} # type: CompletionItemDefaults
211-
errors = [] # type: List[Error]
212-
flags = 0 # int
209+
items: List[sublime.CompletionItem] = []
210+
item_defaults: CompletionItemDefaults = {}
211+
errors: List[Error] = []
212+
flags = 0
213213
prefs = userprefs()
214214
if prefs.inhibit_snippet_completions:
215215
flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS
@@ -225,7 +225,7 @@ def _resolve_completions_async(self, responses: List[ResolvedCompletions]) -> No
225225
session = weak_session()
226226
if not session:
227227
continue
228-
response_items = [] # type: List[CompletionItem]
228+
response_items: List[CompletionItem] = []
229229
if isinstance(response, dict):
230230
response_items = response["items"] or []
231231
item_defaults = response.get('itemDefaults') or {}
@@ -291,7 +291,7 @@ def _handle_resolve_response_async(self, language_map: Optional[MarkdownLangMap]
291291
detail = self._format_documentation(item.get('detail') or "", language_map)
292292
documentation = self._format_documentation(item.get("documentation") or "", language_map)
293293
if not documentation:
294-
markdown = {"kind": MarkupKind.Markdown, "value": "*No documentation available.*"} # type: MarkupContent
294+
markdown: MarkupContent = {"kind": MarkupKind.Markdown, "value": "*No documentation available.*"}
295295
# No need for a language map here
296296
documentation = self._format_documentation(markdown, None)
297297
minihtml_content = ""
@@ -337,7 +337,7 @@ def run(self, edit: sublime.Edit, event: Optional[dict] = None) -> None:
337337

338338
class LspSelectCompletionCommand(LspTextCommand):
339339

340-
completions = {} # type: Dict[SessionName, CompletionsStore]
340+
completions: Dict[SessionName, CompletionsStore] = {}
341341

342342
def run(self, edit: sublime.Edit, index: int, session_name: str) -> None:
343343
items, item_defaults = LspSelectCompletionCommand.completions[session_name]

plugin/core/active_request.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ def __init__(self, sv: SessionViewProtocol, request_id: int, request: Request) -
1818
self.weaksv = ref(sv)
1919
self.request_id = request_id
2020
self.request = request
21-
self.progress = None # type: Optional[ProgressReporter]
21+
self.progress: Optional[ProgressReporter] = None
2222
# `request.progress` is either a boolean or a string. If it's a boolean, then that signals that the server does
2323
# not support client-initiated progress. However, for some requests we still want to notify some kind of
2424
# progress to the end-user. This is communicated by the boolean value being "True".

plugin/core/collections.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def __init__(self, d: Optional[Dict[str, Any]] = None) -> None:
1616
1717
:param d: An existing dictionary.
1818
"""
19-
self._d = {} # type: Dict[str, Any]
19+
self._d: Dict[str, Any] = {}
2020
if d is not None:
2121
self.update(d)
2222

@@ -40,7 +40,7 @@ def get(self, path: Optional[str] = None) -> Any:
4040
"""
4141
if path is None:
4242
return self._d
43-
current = self._d # type: Any
43+
current: Any = self._d
4444
keys = path.split('.')
4545
for key in keys:
4646
if isinstance(current, dict):
@@ -50,7 +50,7 @@ def get(self, path: Optional[str] = None) -> Any:
5050
return current
5151

5252
def walk(self, path: str) -> Generator[Any, None, None]:
53-
current = self._d # type: Any
53+
current: Any = self._d
5454
keys = path.split('.')
5555
for key in keys:
5656
if isinstance(current, dict):

plugin/core/configurations.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@ class WindowConfigManager(object):
2828
def __init__(self, window: sublime.Window, global_configs: Dict[str, ClientConfig]) -> None:
2929
self._window = window
3030
self._global_configs = global_configs
31-
self._disabled_for_session = set() # type: Set[str]
32-
self._crashes = {} # type: Dict[str, Deque[datetime]]
33-
self.all = {} # type: Dict[str, ClientConfig]
34-
self._change_listeners = WeakSet() # type: WeakSet[WindowConfigChangeListener]
31+
self._disabled_for_session: Set[str] = set()
32+
self._crashes: Dict[str, Deque[datetime]] = {}
33+
self.all: Dict[str, ClientConfig] = {}
34+
self._change_listeners: WeakSet[WindowConfigChangeListener] = WeakSet()
3535
self._reload_configs(notify_listeners=False)
3636

3737
def add_change_listener(self, listener: WindowConfigChangeListener) -> None:

plugin/core/constants.py

+14-14
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@
7171
KIND_REFACTOR = (sublime.KIND_ID_COLOR_CYANISH, "r", "Refactor")
7272
KIND_SOURCE = (sublime.KIND_ID_COLOR_PURPLISH, "s", "Source")
7373

74-
COMPLETION_KINDS = {
74+
COMPLETION_KINDS: Dict[CompletionItemKind, SublimeKind] = {
7575
CompletionItemKind.Text: KIND_TEXT,
7676
CompletionItemKind.Method: KIND_METHOD,
7777
CompletionItemKind.Function: KIND_FUNCTION,
@@ -97,9 +97,9 @@
9797
CompletionItemKind.Event: KIND_EVENT,
9898
CompletionItemKind.Operator: KIND_OPERATOR,
9999
CompletionItemKind.TypeParameter: KIND_TYPEPARAMETER
100-
} # type: Dict[CompletionItemKind, SublimeKind]
100+
}
101101

102-
SYMBOL_KINDS = {
102+
SYMBOL_KINDS: Dict[SymbolKind, SublimeKind] = {
103103
SymbolKind.File: KIND_FILE,
104104
SymbolKind.Module: KIND_MODULE,
105105
SymbolKind.Namespace: KIND_NAMESPACE,
@@ -126,45 +126,45 @@
126126
SymbolKind.Event: KIND_EVENT,
127127
SymbolKind.Operator: KIND_OPERATOR,
128128
SymbolKind.TypeParameter: KIND_TYPEPARAMETER
129-
} # type: Dict[SymbolKind, SublimeKind]
129+
}
130130

131-
DIAGNOSTIC_KINDS = {
131+
DIAGNOSTIC_KINDS: Dict[DiagnosticSeverity, SublimeKind] = {
132132
DiagnosticSeverity.Error: KIND_ERROR,
133133
DiagnosticSeverity.Warning: KIND_WARNING,
134134
DiagnosticSeverity.Information: KIND_INFORMATION,
135135
DiagnosticSeverity.Hint: KIND_HINT
136-
} # type: Dict[DiagnosticSeverity, SublimeKind]
136+
}
137137

138-
CODE_ACTION_KINDS = {
138+
CODE_ACTION_KINDS: Dict[CodeActionKind, SublimeKind] = {
139139
CodeActionKind.QuickFix: KIND_QUICKFIX,
140140
CodeActionKind.Refactor: KIND_REFACTOR,
141141
CodeActionKind.Source: KIND_SOURCE
142-
} # type: Dict[CodeActionKind, SublimeKind]
142+
}
143143

144144

145-
DOCUMENT_HIGHLIGHT_KIND_NAMES = {
145+
DOCUMENT_HIGHLIGHT_KIND_NAMES: Dict[DocumentHighlightKind, str] = {
146146
DocumentHighlightKind.Text: "text",
147147
DocumentHighlightKind.Read: "read",
148148
DocumentHighlightKind.Write: "write"
149-
} # type: Dict[DocumentHighlightKind, str]
149+
}
150150

151151

152152
# Symbol scope to kind mapping, based on https://github.com/sublimetext-io/docs.sublimetext.io/issues/30
153-
SUBLIME_KIND_SCOPES = {
153+
SUBLIME_KIND_SCOPES: Dict[SublimeKind, str] = {
154154
sublime.KIND_KEYWORD: "keyword | storage.modifier | storage.type | keyword.declaration | variable.language | constant.language", # noqa: E501
155155
sublime.KIND_TYPE: "entity.name.type | entity.name.class | entity.name.enum | entity.name.trait | entity.name.struct | entity.name.impl | entity.name.interface | entity.name.union | support.type | support.class", # noqa: E501
156156
sublime.KIND_FUNCTION: "entity.name.function | entity.name.method | entity.name.macro | meta.method entity.name.function | support.function | meta.function-call variable.function | meta.function-call support.function | support.method | meta.method-call variable.function", # noqa: E501
157157
sublime.KIND_NAMESPACE: "entity.name.module | entity.name.namespace | support.module | support.namespace",
158158
sublime.KIND_NAVIGATION: "entity.name.definition | entity.name.label | entity.name.section",
159159
sublime.KIND_MARKUP: "entity.other.attribute-name | entity.name.tag | meta.toc-list.id.html",
160160
sublime.KIND_VARIABLE: "entity.name.constant | constant.other | support.constant | variable.other | variable.parameter | variable.other.member | variable.other.readwrite.member" # noqa: E501
161-
} # type: Dict[SublimeKind, str]
161+
}
162162

163-
DOCUMENT_HIGHLIGHT_KIND_SCOPES = {
163+
DOCUMENT_HIGHLIGHT_KIND_SCOPES: Dict[DocumentHighlightKind, str] = {
164164
DocumentHighlightKind.Text: "region.bluish markup.highlight.text.lsp",
165165
DocumentHighlightKind.Read: "region.greenish markup.highlight.read.lsp",
166166
DocumentHighlightKind.Write: "region.yellowish markup.highlight.write.lsp"
167-
} # type: Dict[DocumentHighlightKind, str]
167+
}
168168

169169
SEMANTIC_TOKENS_MAP = {
170170
"namespace": "variable.other.namespace.lsp",

plugin/core/css.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __init__(self) -> None:
1515
self.annotations_classname = "lsp_annotation"
1616

1717

18-
_css = None # type: Optional[CSS]
18+
_css: Optional[CSS] = None
1919

2020

2121
def load() -> None:

plugin/core/diagnostics_storage.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ def filter_map_diagnostics_async(
4545
not more than once. Items and results are ordered as they came in from the server.
4646
"""
4747
for uri, diagnostics in self.items():
48-
results = list(filter(None, map(functools.partial(f, uri), filter(pred, diagnostics)))) # type: List[T]
48+
results: List[T] = list(filter(None, map(functools.partial(f, uri), filter(pred, diagnostics))))
4949
if results:
5050
yield uri, results
5151

plugin/core/edit.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212

1313
def parse_workspace_edit(workspace_edit: WorkspaceEdit) -> WorkspaceChanges:
14-
changes = {} # type: WorkspaceChanges
14+
changes: WorkspaceChanges = {}
1515
document_changes = workspace_edit.get('documentChanges')
1616
if isinstance(document_changes, list):
1717
for document_change in document_changes:

plugin/core/file_watcher.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313

1414
def lsp_watch_kind_to_file_watcher_event_types(kind: WatchKind) -> List[FileWatcherEventType]:
15-
event_types = [] # type: List[FileWatcherEventType]
15+
event_types: List[FileWatcherEventType] = []
1616
if kind & WatchKind.Create:
1717
event_types.append('create')
1818
if kind & WatchKind.Change:
@@ -78,7 +78,7 @@ def destroy(self) -> None:
7878
pass
7979

8080

81-
watcher_implementation = None # type: Optional[Type[FileWatcher]]
81+
watcher_implementation: Optional[Type[FileWatcher]] = None
8282

8383

8484
def register_file_watcher_implementation(file_watcher: Type[FileWatcher]) -> None:

plugin/core/input_handlers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,8 @@ def __init__(self, command: sublime_plugin.WindowCommand, args: Dict[str, Any])
106106
self.command = command
107107
self.args = args
108108
self.text = getattr(command, '_text', '')
109-
self.listener = None # type: Optional[sublime_plugin.TextChangeListener]
110-
self.input_view = None # type: Optional[sublime.View]
109+
self.listener: Optional[sublime_plugin.TextChangeListener] = None
110+
self.input_view: Optional[sublime.View] = None
111111

112112
def attach_listener(self) -> None:
113113
for buffer in sublime._buffers(): # type: ignore

0 commit comments

Comments
 (0)