diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c02c5c37..c42d0fab 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -17,7 +17,7 @@ jobs: strategy: fail-fast: false matrix: - PYTHON_VERSION: ['3.8'] + PYTHON_VERSION: ['3.9'] timeout-minutes: 10 steps: - uses: actions/cache@v1 diff --git a/.github/workflows/static.yml b/.github/workflows/static.yml index 6ec4345d..881a0aa6 100644 --- a/.github/workflows/static.yml +++ b/.github/workflows/static.yml @@ -30,9 +30,7 @@ jobs: - uses: actions/checkout@v4 - uses: actions/setup-python@v5 with: - # TODO: check with Python 3, but need to fix the - # errors first - python-version: '3.8' + python-version: '3.9' architecture: 'x64' - run: python -m pip install --upgrade pip setuptools jsonschema # If we don't install pycodestyle, pylint will throw an unused-argument error in pylsp/plugins/pycodestyle_lint.py:72 diff --git a/.github/workflows/test-linux.yml b/.github/workflows/test-linux.yml index 89277d67..7a7f2f6e 100644 --- a/.github/workflows/test-linux.yml +++ b/.github/workflows/test-linux.yml @@ -24,7 +24,7 @@ jobs: strategy: fail-fast: false matrix: - PYTHON_VERSION: ['3.10', '3.9', '3.8'] + PYTHON_VERSION: ['3.11', '3.10', '3.9'] timeout-minutes: 10 steps: - uses: actions/cache@v4 diff --git a/.github/workflows/test-mac.yml b/.github/workflows/test-mac.yml index d9e4818f..a92c82a8 100644 --- a/.github/workflows/test-mac.yml +++ b/.github/workflows/test-mac.yml @@ -24,7 +24,7 @@ jobs: strategy: fail-fast: false matrix: - PYTHON_VERSION: ['3.10', '3.9', '3.8'] + PYTHON_VERSION: ['3.11', '3.10', '3.9'] timeout-minutes: 10 steps: - uses: actions/cache@v4 diff --git a/.github/workflows/test-win.yml b/.github/workflows/test-win.yml index 1db41154..8ecd3429 100644 --- a/.github/workflows/test-win.yml +++ b/.github/workflows/test-win.yml @@ -24,7 +24,7 @@ jobs: strategy: fail-fast: false matrix: - PYTHON_VERSION: ['3.10', '3.9', '3.8'] + PYTHON_VERSION: ['3.11', '3.10', '3.9'] timeout-minutes: 10 steps: - uses: actions/cache@v4 diff --git a/pylsp/__main__.py b/pylsp/__main__.py index 44aa3cfa..abc0a0bb 100644 --- a/pylsp/__main__.py +++ b/pylsp/__main__.py @@ -20,7 +20,7 @@ start_ws_lang_server, ) -LOG_FORMAT = "%(asctime)s {0} - %(levelname)s - %(name)s - %(message)s".format( +LOG_FORMAT = "%(asctime)s {} - %(levelname)s - %(name)s - %(message)s".format( time.localtime().tm_zone ) @@ -98,7 +98,7 @@ def _configure_logger(verbose=0, log_config=None, log_file=None) -> None: root_logger = logging.root if log_config: - with open(log_config, "r", encoding="utf-8") as f: + with open(log_config, encoding="utf-8") as f: logging.config.dictConfig(json.load(f)) else: formatter = logging.Formatter(LOG_FORMAT) diff --git a/pylsp/_utils.py b/pylsp/_utils.py index b96df5a9..644533df 100644 --- a/pylsp/_utils.py +++ b/pylsp/_utils.py @@ -9,7 +9,7 @@ import re import threading import time -from typing import List, Optional +from typing import Optional import docstring_to_markdown import jedi @@ -78,7 +78,7 @@ def find_parents(root, path, names): Args: path (str): The file path to start searching up from. - names (List[str]): The file/directory names to look for. + names (list[str]): The file/directory names to look for. root (str): The directory at which to stop recursing upwards. Note: @@ -198,7 +198,7 @@ def wrap_signature(signature): SERVER_SUPPORTED_MARKUP_KINDS = {"markdown", "plaintext"} -def choose_markup_kind(client_supported_markup_kinds: List[str]): +def choose_markup_kind(client_supported_markup_kinds: list[str]): """Choose a markup kind supported by both client and the server. This gives priority to the markup kinds provided earlier on the client preference list. @@ -210,7 +210,7 @@ def choose_markup_kind(client_supported_markup_kinds: List[str]): def format_docstring( - contents: str, markup_kind: str, signatures: Optional[List[str]] = None + contents: str, markup_kind: str, signatures: Optional[list[str]] = None ): """Transform the provided docstring into a MarkupContent object. diff --git a/pylsp/config/config.py b/pylsp/config/config.py index 815f8fd2..7b201824 100644 --- a/pylsp/config/config.py +++ b/pylsp/config/config.py @@ -3,8 +3,9 @@ import logging import sys +from collections.abc import Mapping, Sequence from functools import lru_cache -from typing import List, Mapping, Sequence, Union +from typing import Union import pluggy from pluggy._hooks import HookImpl @@ -32,7 +33,7 @@ def _hookexec( methods: Sequence[HookImpl], kwargs: Mapping[str, object], firstresult: bool, - ) -> Union[object, List[object]]: + ) -> Union[object, list[object]]: # called from all hookcaller instances. # enable_tracing will set its own wrapping function at self._inner_hookexec try: diff --git a/pylsp/plugins/_resolvers.py b/pylsp/plugins/_resolvers.py index 44d6d882..dcfd06ab 100644 --- a/pylsp/plugins/_resolvers.py +++ b/pylsp/plugins/_resolvers.py @@ -88,7 +88,7 @@ def resolve(self, completion): def format_label(completion, sig): if sig and completion.type in ("function", "method"): params = ", ".join(param.name for param in sig[0].params) - label = "{}({})".format(completion.name, params) + label = f"{completion.name}({params})" return label return completion.name @@ -115,7 +115,7 @@ def format_snippet(completion, sig): snippet_completion["insertTextFormat"] = lsp.InsertTextFormat.Snippet snippet = completion.name + "(" for i, param in enumerate(positional_args): - snippet += "${%s:%s}" % (i + 1, param.name) + snippet += "${{{}:{}}}".format(i + 1, param.name) if i < len(positional_args) - 1: snippet += ", " snippet += ")$0" diff --git a/pylsp/plugins/_rope_task_handle.py b/pylsp/plugins/_rope_task_handle.py index 8bc13c1d..5e278ee5 100644 --- a/pylsp/plugins/_rope_task_handle.py +++ b/pylsp/plugins/_rope_task_handle.py @@ -1,7 +1,8 @@ from __future__ import annotations import logging -from typing import Callable, ContextManager, List, Optional, Sequence +from collections.abc import Sequence +from typing import Callable, ContextManager from rope.base.taskhandle import BaseJobSet, BaseTaskHandle @@ -19,13 +20,13 @@ class PylspJobSet(BaseJobSet): _report_iter: ContextManager job_name: str = "" - def __init__(self, count: Optional[int], report_iter: ContextManager) -> None: + def __init__(self, count: int | None, report_iter: ContextManager) -> None: if count is not None: self.count = count self._reporter = report_iter.__enter__() self._report_iter = report_iter - def started_job(self, name: Optional[str]) -> None: + def started_job(self, name: str | None) -> None: if name: self.job_name = name @@ -42,7 +43,7 @@ def finished_job(self) -> None: def check_status(self) -> None: pass - def get_percent_done(self) -> Optional[float]: + def get_percent_done(self) -> float | None: if self.count == 0: return 0 return (self.done / self.count) * 100 @@ -66,8 +67,8 @@ def _report(self) -> None: class PylspTaskHandle(BaseTaskHandle): name: str - observers: List - job_sets: List[PylspJobSet] + observers: list + job_sets: list[PylspJobSet] stopped: bool workspace: Workspace _report: Callable[[str, str], None] @@ -77,7 +78,7 @@ def __init__(self, workspace: Workspace) -> None: self.job_sets = [] self.observers = [] - def create_jobset(self, name="JobSet", count: Optional[int] = None): + def create_jobset(self, name="JobSet", count: int | None = None): report_iter = self.workspace.report_progress( name, None, None, skip_token_initialization=True ) @@ -89,7 +90,7 @@ def create_jobset(self, name="JobSet", count: Optional[int] = None): def stop(self) -> None: pass - def current_jobset(self) -> Optional[BaseJobSet]: + def current_jobset(self) -> BaseJobSet | None: pass def add_observer(self) -> None: diff --git a/pylsp/plugins/definition.py b/pylsp/plugins/definition.py index 67abfb71..1ddc03a0 100644 --- a/pylsp/plugins/definition.py +++ b/pylsp/plugins/definition.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING, Any, Dict, List +from typing import TYPE_CHECKING, Any import jedi @@ -23,7 +23,7 @@ def _resolve_definition( - maybe_defn: Name, script: Script, settings: Dict[str, Any] + maybe_defn: Name, script: Script, settings: dict[str, Any] ) -> Name: for _ in range(MAX_JEDI_GOTO_HOPS): if maybe_defn.is_definition() or maybe_defn.module_path != script.path: @@ -43,8 +43,8 @@ def _resolve_definition( @hookimpl def pylsp_definitions( - config: Config, document: Document, position: Dict[str, int] -) -> List[Dict[str, Any]]: + config: Config, document: Document, position: dict[str, int] +) -> list[dict[str, Any]]: settings = config.plugin_settings("jedi_definition") code_position = _utils.position_to_jedi_linecolumn(document, position) script = document.jedi_script(use_document_path=True) diff --git a/pylsp/plugins/flake8_lint.py b/pylsp/plugins/flake8_lint.py index 74e2664c..0ac91855 100644 --- a/pylsp/plugins/flake8_lint.py +++ b/pylsp/plugins/flake8_lint.py @@ -135,7 +135,7 @@ def run_flake8(flake8_executable, args, document, source): cmd = [flake8_executable] cmd.extend(args) p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, **popen_kwargs) - except IOError: + except OSError: log.debug( "Can't execute %s. Trying with '%s -m flake8'", flake8_executable, @@ -165,9 +165,9 @@ def build_args(options): arg = "--{}={}".format(arg_name, ",".join(arg_val)) elif isinstance(arg_val, bool): if arg_val: - arg = "--{}".format(arg_name) + arg = f"--{arg_name}" else: - arg = "--{}={}".format(arg_name, arg_val) + arg = f"--{arg_name}={arg_val}" args.append(arg) return args diff --git a/pylsp/plugins/pylint_lint.py b/pylsp/plugins/pylint_lint.py index 722e831b..f3415c8a 100644 --- a/pylsp/plugins/pylint_lint.py +++ b/pylsp/plugins/pylint_lint.py @@ -287,7 +287,7 @@ def _run_pylint_stdio(pylint_executable, document, flags): cmd.extend(flags) cmd.extend(["--from-stdin", document.path]) p = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE) - except IOError: + except OSError: log.debug("Can't execute %s. Trying with 'python -m pylint'", pylint_executable) cmd = [sys.executable, "-m", "pylint"] cmd.extend(flags) diff --git a/pylsp/plugins/rope_autoimport.py b/pylsp/plugins/rope_autoimport.py index 12f5d80b..8ba951f7 100644 --- a/pylsp/plugins/rope_autoimport.py +++ b/pylsp/plugins/rope_autoimport.py @@ -2,7 +2,8 @@ import logging import threading -from typing import Any, Dict, Generator, List, Optional, Set, Union +from collections.abc import Generator +from typing import Any, Optional, Union import parso from jedi import Script @@ -36,7 +37,7 @@ def reload_cache( self, config: Config, workspace: Workspace, - files: Optional[List[Document]] = None, + files: Optional[list[Document]] = None, single_thread: Optional[bool] = True, ): if self.is_blocked(): @@ -45,7 +46,7 @@ def reload_cache( memory: bool = config.plugin_settings("rope_autoimport").get("memory", False) rope_config = config.settings().get("rope", {}) autoimport = workspace._rope_autoimport(rope_config, memory) - resources: Optional[List[Resource]] = ( + resources: Optional[list[Resource]] = ( None if files is None else [document._rope_resource(rope_config) for document in files] @@ -65,7 +66,7 @@ def _reload_cache( self, workspace: Workspace, autoimport: AutoImport, - resources: Optional[List[Resource]] = None, + resources: Optional[list[Resource]] = None, ) -> None: task_handle = PylspTaskHandle(workspace) autoimport.generate_cache(task_handle=task_handle, resources=resources) @@ -76,7 +77,7 @@ def is_blocked(self): @hookimpl -def pylsp_settings() -> Dict[str, Dict[str, Dict[str, Any]]]: +def pylsp_settings() -> dict[str, dict[str, dict[str, Any]]]: # Default rope_completion to disabled return { "plugins": { @@ -180,13 +181,13 @@ def _handle_argument(node: NodeOrLeaf, word_node: tree.Leaf): def _process_statements( - suggestions: List[SearchResult], + suggestions: list[SearchResult], doc_uri: str, word: str, autoimport: AutoImport, document: Document, feature: str = "completions", -) -> Generator[Dict[str, Any], None, None]: +) -> Generator[dict[str, Any], None, None]: for suggestion in suggestions: insert_line = autoimport.find_insertion_line(document.source) - 1 start = {"line": insert_line, "character": 0} @@ -220,7 +221,7 @@ def _process_statements( raise ValueError(f"Unknown feature: {feature}") -def get_names(script: Script) -> Set[str]: +def get_names(script: Script) -> set[str]: """Get all names to ignore from the current file.""" raw_names = script.get_names(definitions=True) log.debug(raw_names) @@ -233,7 +234,7 @@ def pylsp_completions( workspace: Workspace, document: Document, position, - ignored_names: Union[Set[str], None], + ignored_names: Union[set[str], None], ): """Get autoimport suggestions.""" if ( @@ -251,7 +252,7 @@ def pylsp_completions( word = word_node.value log.debug(f"autoimport: searching for word: {word}") rope_config = config.settings(document_path=document.path).get("rope", {}) - ignored_names: Set[str] = ignored_names or get_names( + ignored_names: set[str] = ignored_names or get_names( document.jedi_script(use_document_path=True) ) autoimport = workspace._rope_autoimport(rope_config) @@ -303,9 +304,9 @@ def pylsp_code_actions( config: Config, workspace: Workspace, document: Document, - range: Dict, - context: Dict, -) -> List[Dict]: + range: dict, + context: dict, +) -> list[dict]: """ Provide code actions through rope. @@ -317,9 +318,9 @@ def pylsp_code_actions( Current workspace. document : pylsp.workspace.Document Document to apply code actions on. - range : Dict + range : dict Range argument given by pylsp. Not used here. - context : Dict + context : dict CodeActionContext given as dict. Returns diff --git a/pylsp/plugins/rope_completion.py b/pylsp/plugins/rope_completion.py index b3a1f066..dc94ddea 100644 --- a/pylsp/plugins/rope_completion.py +++ b/pylsp/plugins/rope_completion.py @@ -22,7 +22,7 @@ def _resolve_completion(completion, data, markup_kind): except Exception as e: log.debug("Failed to resolve Rope completion: %s", e) doc = "" - completion["detail"] = "{0} {1}".format(data.scope or "", data.name) + completion["detail"] = "{} {}".format(data.scope or "", data.name) completion["documentation"] = doc return completion diff --git a/pylsp/python_lsp.py b/pylsp/python_lsp.py index ba41d6aa..6dfad9c3 100644 --- a/pylsp/python_lsp.py +++ b/pylsp/python_lsp.py @@ -7,7 +7,7 @@ import threading import uuid from functools import partial -from typing import Any, Dict, List +from typing import Any try: import ujson as json @@ -382,7 +382,7 @@ def watch_parent_process(pid): def m_initialized(self, **_kwargs) -> None: self._hook("pylsp_initialized") - def code_actions(self, doc_uri: str, range: Dict, context: Dict): + def code_actions(self, doc_uri: str, range: dict, context: dict): return flatten( self._hook("pylsp_code_actions", doc_uri, range=range, context=context) ) @@ -471,7 +471,7 @@ def _lint_notebook_document(self, notebook_document, workspace) -> None: random_uri = str(uuid.uuid4()) # cell_list helps us map the diagnostics back to the correct cell later. - cell_list: List[Dict[str, Any]] = [] + cell_list: list[dict[str, Any]] = [] offset = 0 total_source = "" diff --git a/pylsp/uris.py b/pylsp/uris.py index cba5b290..8ebd8e31 100644 --- a/pylsp/uris.py +++ b/pylsp/uris.py @@ -61,7 +61,7 @@ def to_fs_path(uri): if netloc and path and scheme == "file": # unc path: file://shares/c$/far/boo - value = "//{}{}".format(netloc, path) + value = f"//{netloc}{path}" elif RE_DRIVE_LETTER_PATH.match(path): # windows drive letter: file:///C:/far/boo diff --git a/pylsp/workspace.py b/pylsp/workspace.py index 005c177d..290b95ee 100644 --- a/pylsp/workspace.py +++ b/pylsp/workspace.py @@ -7,9 +7,10 @@ import os import re import uuid +from collections.abc import Generator from contextlib import contextmanager from threading import RLock -from typing import Callable, Generator, List, Optional +from typing import Callable, Optional import jedi @@ -436,7 +437,7 @@ def lines(self): @lock def source(self): if self._source is None: - with io.open(self.path, "r", encoding="utf-8") as f: + with open(self.path, encoding="utf-8") as f: return f.read() return self._source @@ -625,7 +626,7 @@ def __init__( def __str__(self): return "Notebook with URI '%s'" % str(self.uri) - def add_cells(self, new_cells: List, start: int) -> None: + def add_cells(self, new_cells: list, start: int) -> None: self.cells[start:start] = new_cells def remove_cells(self, start: int, delete_count: int) -> None: diff --git a/pyproject.toml b/pyproject.toml index e29a5e2f..583b25a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ authors = [{name = "Python Language Server Contributors"}] description = "Python Language Server for the Language Server Protocol" readme = "README.md" license = {text = "MIT"} -requires-python = ">=3.8" +requires-python = ">=3.9" dependencies = [ "docstring-to-markdown", "importlib_metadata>=4.8.3;python_version<\"3.10\"", @@ -120,8 +120,8 @@ exclude = [ line-length = 88 indent-width = 4 -# Assume Python 3.8 -target-version = "py38" +# Assume Python 3.9 +target-version = "py39" [tool.ruff.lint] # https://docs.astral.sh/ruff/rules/ diff --git a/test/plugins/test_autoimport.py b/test/plugins/test_autoimport.py index dbad8d02..cbe3dde1 100644 --- a/test/plugins/test_autoimport.py +++ b/test/plugins/test_autoimport.py @@ -1,6 +1,6 @@ # Copyright 2022- Python Language Server Contributors. -from typing import Any, Dict, List +from typing import Any from unittest.mock import Mock, patch import jedi @@ -26,14 +26,14 @@ DOC_URI = uris.from_fs_path(__file__) -def contains_autoimport_completion(suggestion: Dict[str, Any], module: str) -> bool: +def contains_autoimport_completion(suggestion: dict[str, Any], module: str) -> bool: """Checks if `suggestion` contains an autoimport completion for `module`.""" return suggestion.get("label", "") == module and "import" in suggestion.get( "detail", "" ) -def contains_autoimport_quickfix(suggestion: Dict[str, Any], module: str) -> bool: +def contains_autoimport_quickfix(suggestion: dict[str, Any], module: str) -> bool: """Checks if `suggestion` contains an autoimport quick fix for `module`.""" return suggestion.get("title", "") == f"import {module}" @@ -78,7 +78,7 @@ def should_insert(phrase: str, position: int): return _should_insert(expr, word_node) -def check_dict(query: Dict, results: List[Dict]) -> bool: +def check_dict(query: dict, results: list[dict]) -> bool: for result in results: if all(result[key] == query[key] for key in query.keys()): return True diff --git a/test/plugins/test_completion.py b/test/plugins/test_completion.py index b8de8912..3ba8dbdd 100644 --- a/test/plugins/test_completion.py +++ b/test/plugins/test_completion.py @@ -5,7 +5,7 @@ import os import sys from pathlib import Path -from typing import Dict, NamedTuple +from typing import NamedTuple import pytest @@ -66,7 +66,7 @@ class TypeCase(NamedTuple): # fmt: off -TYPE_CASES: Dict[str, TypeCase] = { +TYPE_CASES: dict[str, TypeCase] = { "variable": TypeCase( document="test = 1\ntes", position={"line": 1, "character": 3}, diff --git a/test/plugins/test_flake8_lint.py b/test/plugins/test_flake8_lint.py index e7b6b001..d8199d63 100644 --- a/test/plugins/test_flake8_lint.py +++ b/test/plugins/test_flake8_lint.py @@ -125,20 +125,20 @@ def test_flake8_respecting_configuration(workspace) -> None: def test_flake8_config_param(workspace) -> None: with patch("pylsp.plugins.flake8_lint.Popen") as popen_mock: mock_instance = popen_mock.return_value - mock_instance.communicate.return_value = [bytes(), bytes()] + mock_instance.communicate.return_value = [b"", b""] flake8_conf = "/tmp/some.cfg" workspace._config.update({"plugins": {"flake8": {"config": flake8_conf}}}) _name, doc = temp_document(DOC, workspace) flake8_lint.pylsp_lint(workspace, doc) (call_args,) = popen_mock.call_args[0] assert "flake8" in call_args - assert "--config={}".format(flake8_conf) in call_args + assert f"--config={flake8_conf}" in call_args def test_flake8_executable_param(workspace) -> None: with patch("pylsp.plugins.flake8_lint.Popen") as popen_mock: mock_instance = popen_mock.return_value - mock_instance.communicate.return_value = [bytes(), bytes()] + mock_instance.communicate.return_value = [b"", b""] flake8_executable = "/tmp/flake8" workspace._config.update( @@ -187,7 +187,7 @@ def test_flake8_multiline(workspace) -> None: with patch("pylsp.plugins.flake8_lint.Popen") as popen_mock: mock_instance = popen_mock.return_value - mock_instance.communicate.return_value = [bytes(), bytes()] + mock_instance.communicate.return_value = [b"", b""] doc = workspace.get_document(doc_uri) flake8_lint.pylsp_lint(workspace, doc) diff --git a/test/test_utils.py b/test/test_utils.py index 966c469e..7ed6214f 100644 --- a/test/test_utils.py +++ b/test/test_utils.py @@ -6,7 +6,7 @@ import sys import time from threading import Thread -from typing import Any, Dict, List +from typing import Any from unittest import mock from docstring_to_markdown import UnknownFormatError @@ -19,7 +19,7 @@ CALL_TIMEOUT_IN_SECONDS = 30 -def send_notebook_did_open(client, cells: List[str]) -> None: +def send_notebook_did_open(client, cells: list[str]) -> None: """ Sends a notebookDocument/didOpen notification with the given python cells. @@ -31,7 +31,7 @@ def send_notebook_did_open(client, cells: List[str]) -> None: ) -def notebook_with_python_cells(cells: List[str]): +def notebook_with_python_cells(cells: list[str]): """ Create a notebook document with the given python cells. @@ -61,7 +61,7 @@ def notebook_with_python_cells(cells: List[str]): } -def send_initialize_request(client, initialization_options: Dict[str, Any] = None): +def send_initialize_request(client, initialization_options: dict[str, Any] = None): return client._endpoint.request( "initialize", {