Skip to content

Commit

Permalink
Use ruff for linting and formatting.
Browse files Browse the repository at this point in the history
- Removed unused typing imports.
- Renamed ambiguous variable.
- Fix dict literal usage.
- Ruff formatting.
- Removed unnecessary trailing commas.
  • Loading branch information
jonathanslenders committed Nov 3, 2023
1 parent 91d2c35 commit 6c2d650
Show file tree
Hide file tree
Showing 15 changed files with 75 additions and 77 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion ptpython/completer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion ptpython/contrib/asyncssh_repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions ptpython/entry_points/run_ptpython.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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."
)
Expand Down
3 changes: 2 additions & 1 deletion ptpython/history_browser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -107,6 +107,7 @@

class BORDER:
"Box drawing characters."

HORIZONTAL = "\u2501"
VERTICAL = "\u2503"
TOP_LEFT = "\u250f"
Expand Down
22 changes: 10 additions & 12 deletions ptpython/layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 (
Expand Down Expand Up @@ -60,7 +56,6 @@
SystemToolbar,
ValidationToolbar,
)
from pygments.lexers import PythonLexer

from .filters import HasSignature, ShowDocstring, ShowSidebar, ShowSignature
from .prompt_style import PromptStyle
Expand All @@ -74,6 +69,7 @@

class CompletionVisualisation(Enum):
"Visualisation method for the completions."

NONE = "none"
POP_UP = "pop-up"
MULTI_COLUMN = "multi-column"
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
)
Expand Down
2 changes: 1 addition & 1 deletion ptpython/lexer.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
21 changes: 5 additions & 16 deletions ptpython/python_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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",
Expand Down
12 changes: 6 additions & 6 deletions ptpython/repl.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions ptpython/signatures.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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 = {")": "(", "}": "{", "]": "["}
Expand Down
2 changes: 0 additions & 2 deletions ptpython/style.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
12 changes: 1 addition & 11 deletions ptpython/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion ptpython/validator.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
47 changes: 34 additions & 13 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"]
10 changes: 6 additions & 4 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -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={
Expand Down

0 comments on commit 6c2d650

Please sign in to comment.