Skip to content

Commit

Permalink
Update pyright and Ruff
Browse files Browse the repository at this point in the history
  • Loading branch information
Avasam committed Oct 3, 2023
1 parent 2c2728c commit 79d6234
Show file tree
Hide file tree
Showing 12 changed files with 34 additions and 42 deletions.
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ repos:
- id: pretty-format-ini
args: [--autofix]
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: "v0.0.290" # Must match requirements-dev.txt
rev: "v0.0.292" # Must match requirements-dev.txt
hooks:
- id: ruff
args: [--fix]
Expand Down
8 changes: 4 additions & 4 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -87,20 +87,20 @@
// Important to follow the config in pyrightconfig.json
"python.analysis.useLibraryCodeForTypes": false,
"python.analysis.diagnosticMode": "workspace",
"python.linting.enabled": true,
"ruff.importStrategy": "fromEnvironment",
// Use the Ruff extension instead
"isort.check": false,
// linting/formatting options deprecated, use dedicated extensions instead
// https://github.com/microsoft/vscode-python/wiki/Migration-to-Python-Tools-Extensions
"python.linting.enabled": false,
"python.linting.banditEnabled": false,
"python.linting.flake8Enabled": false,
"python.linting.prospectorEnabled": false,
"python.linting.pycodestyleEnabled": false,
"python.linting.pylamaEnabled": false,
"python.linting.pylintEnabled": false,
// Use the autopep8 extension instead
"python.formatting.provider": "none",
// Use Pyright/Pylance instead
"python.linting.mypyEnabled": false,
"python.formatting.provider": "none",
"powershell.codeFormatting.pipelineIndentationStyle": "IncreaseIndentationForFirstPipeline",
"powershell.codeFormatting.autoCorrectAliases": true,
"powershell.codeFormatting.trimWhitespaceAroundPipe": true,
Expand Down
6 changes: 3 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,10 +57,10 @@ ignore = [
"PERF203", # try-except-in-loop

### FIXME/TODO (no warnings in Ruff yet: https://github.com/charliermarsh/ruff/issues/1256):
"CPY001",
"PTH",
"CPY001", # flake8-copyright
"PTH", # flake8-use-pathlib
# Ignore until linux support
"EXE",
"EXE", # flake8-executable
]

[tool.ruff.per-file-ignores]
Expand Down
2 changes: 1 addition & 1 deletion scripts/requirements-dev.txt
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
# Linters & Formatters
add-trailing-comma>=3.1.0 # Must match .pre-commit-config.yaml
autopep8>=2.0.4 # Must match .pre-commit-config.yaml
ruff>=0.0.290 # Ignore @override for bad-dunder-name # Must match .pre-commit-config.yaml
ruff>=0.0.292 # Ignore @override for bad-dunder-name # Must match .pre-commit-config.yaml
#
# Run `./scripts/designer.ps1` to quickly open the bundled Qt Designer.
# Can also be downloaded externally as a non-python package
Expand Down
2 changes: 1 addition & 1 deletion scripts/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ certifi
ImageHash>=4.3.1 # Contains type information + setup as package not module
git+https://github.com/boppreh/keyboard.git#egg=keyboard # Fix install on macos and linux-ci https://github.com/boppreh/keyboard/pull/568
numpy>=1.23.2 # Python 3.11 wheels
opencv-python-headless>=4.8.0.76 # Typing fixes
opencv-python-headless>=4.8.1.78 # Typing fixes
packaging
Pillow>=9.2 # gnome-screeshot checks
psutil
Expand Down
9 changes: 7 additions & 2 deletions src/AutoSplit.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,7 +523,7 @@ def __auto_splitter(self): # noqa: PLR0912,PLR0915
# Construct a list of images + loop count tuples.
self.split_images_and_loop_number = list(
flatten(
[(split_image, i + 1) for i in range(split_image.loops)]
((split_image, i + 1) for i in range(split_image.loops))
for split_image
in self.split_images
),
Expand Down Expand Up @@ -921,7 +921,12 @@ def set_preview_image(qlabel: QLabel, image: MatLike | None):
image_format = QtGui.QImage.Format.Format_BGR888
capture = image

qimage = QtGui.QImage(capture.data, width, height, width * channels, image_format)
qimage = QtGui.QImage(
capture.data, # pyright: ignore[reportGeneralTypeIssues] # https://bugreports.qt.io/browse/PYSIDE-2476
width, height,
width *
channels, image_format,
)
qlabel.setPixmap(
QtGui.QPixmap(qimage).scaled(
qlabel.size(),
Expand Down
5 changes: 3 additions & 2 deletions src/AutoSplitImage.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from AutoSplit import AutoSplit


# Resize to these width and height so that FPS performance increases
COMPARISON_RESIZE_WIDTH = 320
COMPARISON_RESIZE_HEIGHT = 240
Expand Down Expand Up @@ -70,15 +71,15 @@ def get_pause_time(self, default: AutoSplit | float):
"""Get image's pause time or fallback to the default value from spinbox."""
if self.__pause_time is not None:
return self.__pause_time
if isinstance(default, float):
if isinstance(default, (float, int)):
return default
return default.settings_dict["default_pause_time"]

def get_similarity_threshold(self, default: AutoSplit | float):
"""Get image's similarity threshold or fallback to the default value from spinbox."""
if self.__similarity_threshold is not None:
return self.__similarity_threshold
if isinstance(default, float):
if isinstance(default, (float, int)):
return default
return default.settings_dict["default_similarity_threshold"]

Expand Down
12 changes: 3 additions & 9 deletions src/capture_method/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from collections import OrderedDict
from dataclasses import dataclass
from enum import Enum, EnumMeta, auto, unique
from itertools import starmap
from typing import TYPE_CHECKING, NoReturn, TypedDict, cast

from _ctypes import COMError
Expand Down Expand Up @@ -201,16 +202,9 @@ async def get_camera_info(index: int, device_name: str):
if resolution is not None \
else None

# Note: Return type required https://github.com/python/typeshed/issues/2652
future = asyncio.gather(
*[
get_camera_info(index, name) for index, name
in enumerate(named_video_inputs)
],
)

return [
camera_info for camera_info
in await future
# Note: Return type required https://github.com/python/typeshed/issues/2652
in await asyncio.gather(*starmap(get_camera_info, enumerate(named_video_inputs)))
if camera_info is not None
]
8 changes: 4 additions & 4 deletions src/hotkeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def __get_hotkey_name(names: list[str]):
Uses keyboard.get_hotkey_name but works with non-english modifiers and keypad
See: https://github.com/boppreh/keyboard/issues/516 .
"""
if len(names) == 0:
if not names:
return ""

if len(names) == 1:
Expand All @@ -192,7 +192,7 @@ def __read_hotkey():
if keyboard_event.event_type == keyboard.KEY_UP:
# Unless keyup is also the very first event,
# which can happen from a very fast press at the same time we start reading
if len(names) == 0:
if not names:
continue
break
key_name = __get_key_name(keyboard_event)
Expand All @@ -209,7 +209,7 @@ def __read_hotkey():
def __remove_key_already_set(autosplit: AutoSplit, key_name: str):
for hotkey in HOTKEYS:
settings_key = f"{hotkey}_hotkey"
if autosplit.settings_dict[settings_key] == key_name: # pyright: ignore[reportGeneralTypeIssues]
if autosplit.settings_dict.get(settings_key) == key_name:
_unhook(getattr(autosplit, f"{hotkey}_hotkey"))
autosplit.settings_dict[settings_key] = "" # pyright: ignore[reportGeneralTypeIssues]
if autosplit.SettingsWidget:
Expand Down Expand Up @@ -258,7 +258,7 @@ def set_hotkey(autosplit: AutoSplit, hotkey: Hotkey, preselected_hotkey_name: st
@fire_and_forget
def read_and_set_hotkey():
try:
hotkey_name = preselected_hotkey_name if preselected_hotkey_name else __read_hotkey()
hotkey_name = preselected_hotkey_name or __read_hotkey()

# Unset hotkey by pressing "Escape". This is the same behaviour as LiveSplit
if hotkey_name == "esc":
Expand Down
7 changes: 1 addition & 6 deletions src/menu_bar.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,7 @@ def hotkey_connect(hotkey: Hotkey):
for hotkey in HOTKEYS:
hotkey_input: QtWidgets.QLineEdit = getattr(self, f"{hotkey}_input")
set_hotkey_hotkey_button: QtWidgets.QPushButton = getattr(self, f"set_{hotkey}_hotkey_button")
hotkey_input.setText(
cast(
str,
self.autosplit.settings_dict[f"{hotkey}_hotkey"], # pyright: ignore[reportGeneralTypeIssues]
),
)
hotkey_input.setText(self.autosplit.settings_dict.get(f"{hotkey}_hotkey", ""))

set_hotkey_hotkey_button.clicked.connect(hotkey_connect(hotkey))
# Make it very clear that hotkeys are not used when auto-controlled
Expand Down
4 changes: 2 additions & 2 deletions src/user_profile.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ def __load_settings_from_file(autosplit: AutoSplit, load_settings_file_path: str
},
)
# TODO: Data Validation / fallbacks ?
autosplit.settings_dict = UserProfileDict(**loaded_settings) # type: ignore[misc]
autosplit.settings_dict = UserProfileDict(**loaded_settings)
autosplit.last_loaded_settings = autosplit.settings_dict

autosplit.x_spinbox.setValue(autosplit.settings_dict["capture_region"]["x"])
Expand All @@ -139,7 +139,7 @@ def __load_settings_from_file(autosplit: AutoSplit, load_settings_file_path: str
remove_all_hotkeys()
if not autosplit.is_auto_controlled:
for hotkey, hotkey_name in [(hotkey, f"{hotkey}_hotkey") for hotkey in HOTKEYS]:
hotkey_value = cast(str, autosplit.settings_dict[hotkey_name]) # pyright: ignore[reportGeneralTypeIssues]
hotkey_value = autosplit.settings_dict.get(hotkey_name)
if hotkey_value:
set_hotkey(autosplit, hotkey, hotkey_value)

Expand Down
11 changes: 4 additions & 7 deletions src/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@
import ctypes.wintypes
import os
import sys
from collections.abc import Callable, Generator, Iterable
from collections.abc import Callable, Iterable
from enum import IntEnum
from itertools import chain
from platform import version
from threading import Thread
from typing import TYPE_CHECKING, Any, TypeVar
Expand Down Expand Up @@ -170,12 +171,8 @@ def wrapped(*args: Any, **kwargs: Any):
return wrapped


def flatten(nested_iterable: Iterable[Iterable[_T]]) -> Generator[_T, None, None]:
return (
item for flatten
in nested_iterable
for item in flatten
)
def flatten(nested_iterable: Iterable[Iterable[_T]]) -> chain[_T]:
return chain(*nested_iterable)


# Environment specifics
Expand Down

0 comments on commit 79d6234

Please sign in to comment.