Skip to content

Commit 9f623e9

Browse files
committed
fix(pyright): Fix or ignore pyright linter issues
1 parent e2b96e8 commit 9f623e9

14 files changed

+115
-26
lines changed

.github/workflows/pyright.yml

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
name: Pyright
2+
3+
on:
4+
pull_request:
5+
paths:
6+
- '**/*.py' # Watch for changes in any Python files
7+
- 'pyproject.toml' # Watch for changes in the pyproject.toml file
8+
push:
9+
paths:
10+
- '**/*.py' # Watch for changes in any Python files
11+
- 'pyproject.toml' # Watch for changes in the pyproject.toml file
12+
workflow_dispatch:
13+
14+
jobs:
15+
pyright:
16+
runs-on: ubuntu-latest
17+
strategy:
18+
matrix:
19+
python-version: ["3.9", "3.12"]
20+
21+
env:
22+
UV_SYSTEM_PYTHON: 1
23+
24+
steps:
25+
- name: Checkout
26+
uses: actions/checkout@v4
27+
28+
# https://docs.astral.sh/uv/guides/integration/github/
29+
- name: Install uv and set the python version
30+
uses: astral-sh/setup-uv@v5
31+
with:
32+
python-version: ${{ matrix.python-version }}
33+
34+
- name: Set up Python ${{ matrix.python-version }}
35+
uses: actions/setup-python@v5
36+
with:
37+
python-version: ${{ matrix.python-version }}
38+
39+
- name: Install dependencies
40+
# these extra packages are required by pyright to validate the python imports
41+
run: |
42+
uv pip install 'pyright==1.1.394' 'argcomplete==3.5.3' 'defusedxml==0.7.1' 'jsonschema==4.23.0' 'matplotlib==3.9.4' 'numpy==2.0.2' 'pillow==11.1.0' 'platformdirs==4.3.6' 'pymavlink==2.4.42' 'pyserial==3.5' 'requests==2.32.3' 'setuptools==75.8.0'
43+
44+
- name: Run pyright
45+
uses: jakebailey/pyright-action@v2
46+
with:
47+
version: PATH

REUSE.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ SPDX-FileCopyrightText = "2024-2025 Amilcar Lucas, 2025 Jonas Vermeulen"
5353
SPDX-License-Identifier = "GPL-3.0-or-later"
5454

5555
[[annotations]]
56-
path = ["cliff.toml", "install_msgfmt.bat", "install_wsl.bash", "pyproject.toml", "pytest.ini", "test_pip_package.sh"]
56+
path = ["pyrightconfig.json", "install_msgfmt.bat", "install_wsl.bash", "pyproject.toml", "pytest.ini", "test_pip_package.sh"]
5757
SPDX-FileCopyrightText = "2024-2025 Amilcar Lucas"
5858
SPDX-License-Identifier = "GPL-3.0-or-later"
5959

ardupilot_methodic_configurator/argparse_check_range.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -36,16 +36,16 @@ def __init__(self, *args, **kwargs) -> None:
3636

3737
def interval(self) -> str:
3838
if hasattr(self, "min"):
39-
_lo = f"[{self.min}"
39+
_lo = f"[{self.min}" # pyright: ignore[reportAttributeAccessIssue]
4040
elif hasattr(self, "inf"):
41-
_lo = f"({self.inf}"
41+
_lo = f"({self.inf}" # pyright: ignore[reportAttributeAccessIssue]
4242
else:
4343
_lo = "(-infinity"
4444

4545
if hasattr(self, "max"):
46-
_up = f"{self.max}]"
46+
_up = f"{self.max}]" # pyright: ignore[reportAttributeAccessIssue]
4747
elif hasattr(self, "sup"):
48-
_up = f"{self.sup})"
48+
_up = f"{self.sup})" # pyright: ignore[reportAttributeAccessIssue]
4949
else:
5050
_up = "+infinity)"
5151

ardupilot_methodic_configurator/backend_flightcontroller.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def __init__(self, reboot_time: int) -> None:
8080
self.__reboot_time = reboot_time
8181
self.__connection_tuples: list[tuple[str, str]] = []
8282
self.discover_connections()
83-
self.master: Union[mavutil.mavlink_connection, None] = None
83+
self.master: Union[mavutil.mavlink_connection, None] = None # pyright: ignore[reportGeneralTypeIssues]
8484
self.comport: Union[mavutil.SerialPort, None] = None
8585
self.fc_parameters: dict[str, float] = {}
8686
self.info = BackendFlightcontrollerInfo()
@@ -583,7 +583,7 @@ def add_argparse_arguments(parser: ArgumentParser) -> ArgumentParser:
583583
'If set to "none" no connection is made.'
584584
" Default is autodetection"
585585
),
586-
).completer = lambda **_: FlightController.__list_serial_ports()
586+
).completer = lambda **_: FlightController.__list_serial_ports() # pyright: ignore[reportAttributeAccessIssue]
587587
parser.add_argument(
588588
"-r",
589589
"--reboot-time",

ardupilot_methodic_configurator/backend_mavftp.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1133,13 +1133,13 @@ def __handle_reset_sessions_reply(self, op, _m) -> MAVFTPReturn:
11331133
"""Handle reset sessions reply."""
11341134
return self.__decode_ftp_ack_and_nack(op)
11351135

1136-
def process_ftp_reply(self, operation_name, timeout=5) -> MAVFTPReturn:
1136+
def process_ftp_reply(self, operation_name, timeout: float = 5) -> MAVFTPReturn:
11371137
"""Execute an FTP operation that requires processing a MAVLink response."""
11381138
start_time = time.time()
11391139
ret = MAVFTPReturn(operation_name, ERR_Fail)
11401140
recv_timeout = 0.1
11411141
assert ( # noqa: S101
1142-
timeout == 0 or timeout > self.ftp_settings.idle_detection_time
1142+
timeout == 0 or timeout > float(self.ftp_settings.idle_detection_time)
11431143
), "timeout must be > settings.idle_detection_time"
11441144
assert recv_timeout < self.ftp_settings.retry_time, "recv_timeout must be < settings.retry_time" # noqa: S101
11451145

ardupilot_methodic_configurator/extract_param_defaults.py

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ def extract_parameter_values(logfile: str, param_type: str = "defaults") -> dict
139139
if not values:
140140
raise SystemExit(NO_DEFAULT_VALUES_MESSAGE)
141141
return values
142-
pname = m.Name
142+
pname = str(m.Name)
143143
if len(pname) > PARAM_NAME_MAX_LEN:
144144
msg = f"Too long parameter name: {pname}"
145145
raise SystemExit(msg)
@@ -150,14 +150,26 @@ def extract_parameter_values(logfile: str, param_type: str = "defaults") -> dict
150150
if pname in values:
151151
continue
152152
if param_type == "defaults":
153-
if hasattr(m, "Default"):
154-
values[pname] = m.Default
153+
if hasattr(m, "Default") and m.Default is not None:
154+
try:
155+
values[pname] = float(m.Default)
156+
except ValueError as e:
157+
msg = f"Error converting {m.Default} to float"
158+
raise SystemExit(msg) from e
155159
elif param_type == "values":
156-
if hasattr(m, "Value"):
157-
values[pname] = m.Value
160+
if hasattr(m, "Value") and m.Value is not None:
161+
try:
162+
values[pname] = float(m.Value)
163+
except ValueError as e:
164+
msg = f"Error converting {m.Value} to float"
165+
raise SystemExit(msg) from e
158166
elif param_type == "non_default_values":
159-
if hasattr(m, "Value") and hasattr(m, "Default") and m.Value != m.Default:
160-
values[pname] = m.Value
167+
if hasattr(m, "Value") and hasattr(m, "Default") and m.Value != m.Default and m.Value is not None:
168+
try:
169+
values[pname] = float(m.Value)
170+
except ValueError as e:
171+
msg = f"Error converting {m.Value} to float"
172+
raise SystemExit(msg) from e
161173
else:
162174
msg = f"Invalid type {param_type}"
163175
raise SystemExit(msg)

ardupilot_methodic_configurator/frontend_tkinter_component_editor.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,13 @@ class VoltageTooHighError(Exception):
210210
}
211211

212212

213+
class MockEvent(tk.Event): # pylint: disable=too-few-public-methods
214+
"""A mock event object that mirrors the structure of a real tkinter event."""
215+
216+
def __init__(self, event_type: tk.EventType) -> None:
217+
self.type = event_type
218+
219+
213220
class ComponentEditorWindow(ComponentEditorWindowBase):
214221
"""
215222
This class validates the user input and handles user interactions
@@ -750,7 +757,7 @@ def validate_data(self) -> bool: # pylint: disable=too-many-branches
750757

751758
validate_function = self.get_validate_function(entry, path)
752759
if validate_function:
753-
mock_focus_out_event = type("", (), {"type": "10"})()
760+
mock_focus_out_event = MockEvent(tk.EventType.FocusOut)
754761
if not validate_function(mock_focus_out_event):
755762
invalid_values = True
756763
if path in {

ardupilot_methodic_configurator/frontend_tkinter_parameter_editor_table.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from logging import critical as logging_critical
1616
from logging import debug as logging_debug
1717
from logging import info as logging_info
18+
from math import nan
1819
from platform import system as platform_system
1920
from sys import exit as sys_exit
2021
from tkinter import messagebox, ttk
@@ -190,8 +191,10 @@ def rename_fc_connection(self, selected_file: str) -> None:
190191
messagebox.showinfo(_("Parameter Renamed"), info_msg.format(**locals()))
191192

192193
def __update_table(self, params: dict[str, Par], fc_parameters: dict[str, float]) -> None:
194+
current_param_name: str = ""
193195
try:
194196
for i, (param_name, param) in enumerate(params.items(), 1):
197+
current_param_name = param_name
195198
param_metadata = self.local_filesystem.doc_dict.get(param_name, None)
196199
param_default = self.local_filesystem.param_default_dict.get(param_name, None)
197200
doc_tooltip = (
@@ -227,7 +230,9 @@ def __update_table(self, params: dict[str, Par], fc_parameters: dict[str, float]
227230
add_button.grid(row=len(params) + 2, column=0, sticky="w", padx=0)
228231

229232
except KeyError as e:
230-
logging_critical(_("Parameter %s not found in the %s file: %s"), param_name, self.current_file, e, exc_info=True)
233+
logging_critical(
234+
_("Parameter %s not found in the %s file: %s"), current_param_name, self.current_file, e, exc_info=True
235+
)
231236
sys_exit(1)
232237

233238
# Configure the table_frame to stretch columns
@@ -640,7 +645,9 @@ def __on_parameter_value_change(self, event: tk.Event, current_file: str, param_
640645
except KeyError as e:
641646
logging_critical(_("Parameter %s not found in the %s file: %s"), param_name, current_file, e, exc_info=True)
642647
sys_exit(1)
643-
valid = True
648+
valid: bool = True
649+
changed: bool = False
650+
p: float = nan
644651
# Check if the input is a valid float
645652
try:
646653
p = float(new_value) # type: ignore[arg-type] # workaround a mypy bug

ardupilot_methodic_configurator/frontend_tkinter_template_overview.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -136,12 +136,12 @@ def _adjust_treeview_column_widths(self) -> None:
136136
for col in self.tree["columns"]:
137137
max_width = 0
138138
for subtitle in col.title().split("\n"):
139-
max_width = max(max_width, tk.font.Font().measure(subtitle))
139+
max_width = max(max_width, tk.font.Font().measure(subtitle)) # pyright: ignore[reportAttributeAccessIssue]
140140

141141
# Iterate over all rows and update the max_width if a wider entry is found
142142
for item in self.tree.get_children():
143143
item_text = self.tree.item(item, "values")[self.tree["columns"].index(col)]
144-
text_width = tk.font.Font().measure(item_text)
144+
text_width = tk.font.Font().measure(item_text) # pyright: ignore[reportAttributeAccessIssue]
145145
max_width = max(max_width, text_width)
146146

147147
# Update the column's width property to accommodate the largest text width

credits/CREDITS.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ Credits also go to these other software projects that helped in developing ArduP
6161
- [ruff](https://docs.astral.sh/ruff/): A fast Python linter.
6262
- [pylint](https://www.pylint.org/): A Python static code analysis tool.
6363
- [mypy](https://mypy-lang.org/): A static type checker for Python.
64+
- [pyright](https://github.com/microsoft/pyright): Pyright is a full-featured, standards-based static type checker for Python.
6465
- [uv](https://docs.astral.sh/uv/): An extremely fast Python package and project manager.
6566
- [grammarly](https://www.grammarly.com/): An AI-powered writing assistant.
6667
- [markdown-lint-cli2](https://github.com/DavidAnson/markdownlint-cli2): A command-line tool for linting Markdown files.

0 commit comments

Comments
 (0)