From 6c2d650649e5003d9ee01c01df508c11c6b28e9b Mon Sep 17 00:00:00 2001 From: Jonathan Slenders Date: Fri, 3 Nov 2023 13:07:14 +0000 Subject: [PATCH] Use ruff for linting and formatting. - Removed unused typing imports. - Renamed ambiguous variable. - Fix dict literal usage. - Ruff formatting. - Removed unnecessary trailing commas. --- .github/workflows/test.yaml | 6 ++-- ptpython/completer.py | 2 +- ptpython/contrib/asyncssh_repl.py | 2 +- ptpython/entry_points/run_ptpython.py | 6 ++-- ptpython/history_browser.py | 3 +- ptpython/layout.py | 22 ++++++------- ptpython/lexer.py | 2 +- ptpython/python_input.py | 21 +++--------- ptpython/repl.py | 12 +++---- ptpython/signatures.py | 3 +- ptpython/style.py | 2 -- ptpython/utils.py | 12 +------ ptpython/validator.py | 2 +- pyproject.toml | 47 +++++++++++++++++++-------- setup.py | 10 +++--- 15 files changed, 75 insertions(+), 77 deletions(-) diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml index 31837db3..9a50f3bc 100644 --- a/.github/workflows/test.yaml +++ b/.github/workflows/test.yaml @@ -22,13 +22,13 @@ jobs: run: | sudo apt remove python3-pip python -m pip install --upgrade pip - python -m pip install . black isort mypy pytest readme_renderer + python -m pip install . ruff mypy pytest readme_renderer pip list - name: Type Checker run: | mypy ptpython - isort -c --profile black ptpython examples setup.py - black --check ptpython examples setup.py + ruff . + ruff format --check . - name: Run Tests run: | ./tests/run_tests.py diff --git a/ptpython/completer.py b/ptpython/completer.py index 85a96d7c..91d66474 100644 --- a/ptpython/completer.py +++ b/ptpython/completer.py @@ -6,7 +6,7 @@ import keyword import re from enum import Enum -from typing import TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Optional, Tuple +from typing import TYPE_CHECKING, Any, Callable, Iterable from prompt_toolkit.completion import ( CompleteEvent, diff --git a/ptpython/contrib/asyncssh_repl.py b/ptpython/contrib/asyncssh_repl.py index 0347aded..051519de 100644 --- a/ptpython/contrib/asyncssh_repl.py +++ b/ptpython/contrib/asyncssh_repl.py @@ -9,7 +9,7 @@ from __future__ import annotations import asyncio -from typing import Any, Optional, TextIO, cast +from typing import Any, TextIO, cast import asyncssh from prompt_toolkit.data_structures import Size diff --git a/ptpython/entry_points/run_ptpython.py b/ptpython/entry_points/run_ptpython.py index 1b4074d4..c0b4078b 100644 --- a/ptpython/entry_points/run_ptpython.py +++ b/ptpython/entry_points/run_ptpython.py @@ -28,7 +28,7 @@ import pathlib import sys from textwrap import dedent -from typing import IO, Optional, Tuple +from typing import IO import appdirs from prompt_toolkit.formatted_text import HTML @@ -72,12 +72,12 @@ def create_parser() -> _Parser: "--light-bg", action="store_true", help="Run on a light background (use dark colors for text).", - ), + ) parser.add_argument( "--dark-bg", action="store_true", help="Run on a dark background (use light colors for text).", - ), + ) parser.add_argument( "--config-file", type=str, help="Location of configuration file." ) diff --git a/ptpython/history_browser.py b/ptpython/history_browser.py index eea81c2e..b667be12 100644 --- a/ptpython/history_browser.py +++ b/ptpython/history_browser.py @@ -7,7 +7,7 @@ from __future__ import annotations from functools import partial -from typing import TYPE_CHECKING, Callable, List, Optional, Set +from typing import TYPE_CHECKING, Callable from prompt_toolkit.application import Application from prompt_toolkit.application.current import get_app @@ -107,6 +107,7 @@ class BORDER: "Box drawing characters." + HORIZONTAL = "\u2501" VERTICAL = "\u2503" TOP_LEFT = "\u250f" diff --git a/ptpython/layout.py b/ptpython/layout.py index d15e52e2..2c1ec15f 100644 --- a/ptpython/layout.py +++ b/ptpython/layout.py @@ -7,7 +7,7 @@ import sys from enum import Enum from inspect import _ParameterKind as ParameterKind -from typing import TYPE_CHECKING, Any, List, Optional, Type +from typing import TYPE_CHECKING, Any from prompt_toolkit.application import get_app from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER @@ -17,11 +17,7 @@ is_done, renderer_height_is_known, ) -from prompt_toolkit.formatted_text import ( - AnyFormattedText, - fragment_list_width, - to_formatted_text, -) +from prompt_toolkit.formatted_text import fragment_list_width, to_formatted_text from prompt_toolkit.formatted_text.base import StyleAndTextTuples from prompt_toolkit.key_binding.vi_state import InputMode from prompt_toolkit.layout.containers import ( @@ -60,7 +56,6 @@ SystemToolbar, ValidationToolbar, ) -from pygments.lexers import PythonLexer from .filters import HasSignature, ShowDocstring, ShowSidebar, ShowSignature from .prompt_style import PromptStyle @@ -74,6 +69,7 @@ class CompletionVisualisation(Enum): "Visualisation method for the completions." + NONE = "none" POP_UP = "pop-up" MULTI_COLUMN = "multi-column" @@ -151,7 +147,7 @@ def goto_next(mouse_event: MouseEvent) -> None: append_category(category) for option in category.options: - append(i, option.title, "%s" % (option.get_current_value(),)) + append(i, option.title, str(option.get_current_value())) i += 1 tokens.pop() # Remove last newline. @@ -302,13 +298,15 @@ def get_text_fragments() -> StyleAndTextTuples: content=Window( FormattedTextControl(get_text_fragments), height=Dimension.exact(1) ), - filter= # Show only when there is a signature - HasSignature(python_input) & + filter=HasSignature(python_input) + & # Signature needs to be shown. - ShowSignature(python_input) & + ShowSignature(python_input) + & # And no sidebar is visible. - ~ShowSidebar(python_input) & + ~ShowSidebar(python_input) + & # Not done yet. ~is_done, ) diff --git a/ptpython/lexer.py b/ptpython/lexer.py index 81924c9d..d925e95c 100644 --- a/ptpython/lexer.py +++ b/ptpython/lexer.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Callable, Optional +from typing import Callable from prompt_toolkit.document import Document from prompt_toolkit.formatted_text import StyleAndTextTuples diff --git a/ptpython/python_input.py b/ptpython/python_input.py index 0c7fef6f..211d36c9 100644 --- a/ptpython/python_input.py +++ b/ptpython/python_input.py @@ -6,18 +6,7 @@ from asyncio import get_event_loop from functools import partial -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Generic, - List, - Mapping, - Optional, - Tuple, - TypeVar, -) +from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, Mapping, TypeVar from prompt_toolkit.application import Application, get_app from prompt_toolkit.auto_suggest import ( @@ -333,7 +322,7 @@ def __init__( # Cursor shapes. self.cursor_shape_config = "Block" - self.all_cursor_shape_configs: Dict[str, AnyCursorShapeConfig] = { + self.all_cursor_shape_configs: dict[str, AnyCursorShapeConfig] = { "Block": CursorShape.BLOCK, "Underline": CursorShape.UNDERLINE, "Beam": CursorShape.BEAM, @@ -607,10 +596,10 @@ def get_values() -> dict[str, Callable[[], bool]]: description="Change the cursor style, possibly according " "to the Vi input mode.", get_current_value=lambda: self.cursor_shape_config, - get_values=lambda: dict( - (s, partial(enable, "cursor_shape_config", s)) + get_values=lambda: { + s: partial(enable, "cursor_shape_config", s) for s in self.all_cursor_shape_configs - ), + }, ), simple_option( title="Paste mode", diff --git a/ptpython/repl.py b/ptpython/repl.py index 02a5075d..3a74c3c3 100644 --- a/ptpython/repl.py +++ b/ptpython/repl.py @@ -18,7 +18,7 @@ import warnings from dis import COMPILER_FLAG_NAMES from enum import Enum -from typing import Any, Callable, ContextManager, Dict, Optional +from typing import Any, Callable, ContextManager from prompt_toolkit.formatted_text import ( HTML, @@ -547,12 +547,12 @@ def _format_exception_output(self, e: BaseException) -> PygmentsTokens: tblist = tblist[line_nr:] break - l = traceback.format_list(tblist) - if l: - l.insert(0, "Traceback (most recent call last):\n") - l.extend(traceback.format_exception_only(t, v)) + tb_list = traceback.format_list(tblist) + if tb_list: + tb_list.insert(0, "Traceback (most recent call last):\n") + tb_list.extend(traceback.format_exception_only(t, v)) - tb_str = "".join(l) + tb_str = "".join(tb_list) # Format exception and write to output. # (We use the default style. Most other styles result diff --git a/ptpython/signatures.py b/ptpython/signatures.py index 5a6f286a..d4cb98c2 100644 --- a/ptpython/signatures.py +++ b/ptpython/signatures.py @@ -10,7 +10,7 @@ import inspect from inspect import Signature as InspectSignature from inspect import _ParameterKind as ParameterKind -from typing import TYPE_CHECKING, Any, Dict, List, Optional, Sequence, Tuple +from typing import TYPE_CHECKING, Any, Sequence from prompt_toolkit.document import Document @@ -203,7 +203,6 @@ def get_signatures_using_eval( running `eval()` over the detected function name. """ # Look for open parenthesis, before cursor position. - text = document.text_before_cursor pos = document.cursor_position - 1 paren_mapping = {")": "(", "}": "{", "]": "["} diff --git a/ptpython/style.py b/ptpython/style.py index 199d5abf..c5a04e58 100644 --- a/ptpython/style.py +++ b/ptpython/style.py @@ -1,7 +1,5 @@ from __future__ import annotations -from typing import Dict - from prompt_toolkit.styles import BaseStyle, Style, merge_styles from prompt_toolkit.styles.pygments import style_from_pygments_cls from prompt_toolkit.utils import is_conemu_ansi, is_windows, is_windows_vt100_supported diff --git a/ptpython/utils.py b/ptpython/utils.py index d973d726..28887d20 100644 --- a/ptpython/utils.py +++ b/ptpython/utils.py @@ -4,17 +4,7 @@ from __future__ import annotations import re -from typing import ( - TYPE_CHECKING, - Any, - Callable, - Dict, - Iterable, - Optional, - Type, - TypeVar, - cast, -) +from typing import TYPE_CHECKING, Any, Callable, Iterable, TypeVar, cast from prompt_toolkit.document import Document from prompt_toolkit.formatted_text import to_formatted_text diff --git a/ptpython/validator.py b/ptpython/validator.py index 3b36d273..91b9c284 100644 --- a/ptpython/validator.py +++ b/ptpython/validator.py @@ -1,6 +1,6 @@ from __future__ import annotations -from typing import Callable, Optional +from typing import Callable from prompt_toolkit.document import Document from prompt_toolkit.validation import ValidationError, Validator diff --git a/pyproject.toml b/pyproject.toml index b356239f..d9d839ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,13 +1,34 @@ -[tool.black] -target-version = ['py36'] - - -[tool.isort] -# isort configuration that is compatible with Black. -multi_line_output = 3 -include_trailing_comma = true -known_first_party = "ptpython" -known_third_party = "prompt_toolkit,pygments,asyncssh" -force_grid_wrap = 0 -use_parentheses = true -line_length = 88 +[tool.ruff] +target-version = "py37" +select = [ + "E", # pycodestyle errors + "W", # pycodestyle warnings + "F", # pyflakes + "C", # flake8-comprehensions + "T", # Print. + "I", # isort + # "B", # flake8-bugbear + "UP", # pyupgrade + "RUF100", # unused-noqa + "Q", # quotes +] +ignore = [ + "E501", # Line too long, handled by black + "C901", # Too complex + "E722", # bare except. +] + + +[tool.ruff.per-file-ignores] +"examples/*" = ["T201"] # Print allowed in examples. +"examples/ptpython_config/config.py" = ["F401"] # Unused imports in config. +"ptpython/entry_points/run_ptipython.py" = ["T201", "F401"] # Print, import usage. +"ptpython/entry_points/run_ptpython.py" = ["T201"] # Print usage. +"ptpython/ipython.py" = ["T100"] # Import usage. +"ptpython/repl.py" = ["T201"] # Print usage. +"tests/run_tests.py" = ["F401"] # Unused imports. + + +[tool.ruff.isort] +known-first-party = ["ptpython"] +known-third-party = ["prompt_toolkit", "pygments", "asyncssh"] diff --git a/setup.py b/setup.py index 18d2911a..ae9838ea 100644 --- a/setup.py +++ b/setup.py @@ -39,12 +39,14 @@ "ptpython = ptpython.entry_points.run_ptpython:run", "ptipython = ptpython.entry_points.run_ptipython:run", "ptpython%s = ptpython.entry_points.run_ptpython:run" % sys.version_info[0], - "ptpython%s.%s = ptpython.entry_points.run_ptpython:run" - % sys.version_info[:2], + "ptpython{}.{} = ptpython.entry_points.run_ptpython:run".format( + *sys.version_info[:2] + ), "ptipython%s = ptpython.entry_points.run_ptipython:run" % sys.version_info[0], - "ptipython%s.%s = ptpython.entry_points.run_ptipython:run" - % sys.version_info[:2], + "ptipython{}.{} = ptpython.entry_points.run_ptipython:run".format( + *sys.version_info[:2] + ), ] }, extras_require={