Skip to content

Commit 3d4d463

Browse files
committed
ruff rules UP for pyupgrade
1 parent cf324f1 commit 3d4d463

7 files changed

Lines changed: 34 additions & 30 deletions

File tree

build_parameters.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -352,7 +352,7 @@ def replace_anchors(source_file, dest_file, version_tag):
352352
For each parameter file generate by param_parse.py, it inserts a version tag in anchors
353353
to do not make confusing in sphinx toctrees.
354354
"""
355-
file_in = open(source_file, "r")
355+
file_in = open(source_file)
356356
file_out = open(dest_file, "w")
357357
found_original_title = False
358358
if "latest" not in version_tag:

frontend/scripts/get_discourse_posts.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
"""
33
Script to get last blog entries on Discourse (https://discuss.ardupilot.org/)
44
"""
5+
from __future__ import annotations
6+
57
import argparse
68
import hashlib
79
import json
@@ -10,7 +12,7 @@
1012
import re
1113
from dataclasses import dataclass
1214
from pathlib import Path
13-
from typing import Any, List, Tuple
15+
from typing import Any
1416

1517
import requests
1618
from requests.adapters import HTTPAdapter
@@ -96,7 +98,7 @@ def execute_http_request_json(self, url: str) -> Any:
9698
except requests.exceptions.RequestException as err:
9799
cache_path = BlogPostsFetcher._get_cache_path(url)
98100
if cache_path.exists():
99-
with open(cache_path, "r", encoding="utf-8") as f:
101+
with open(cache_path, encoding="utf-8") as f:
100102
return json.load(f)
101103
raise RequestExecutionError(f"Request failed with {err}. URL: {url}")
102104

@@ -118,7 +120,7 @@ def get_single_post_text(self, content: Any) -> str:
118120
return str(litem[:140] + ' (...)')
119121

120122
@staticmethod
121-
def get_first_youtube_or_img_link(request: str) -> Tuple[str, bool]:
123+
def get_first_youtube_or_img_link(request: str) -> tuple[str, bool]:
122124
""" Returns the first YouTube link or image link in the request, if any.
123125
True if the link is a Youtube link."""
124126
request_lines = request.splitlines()
@@ -186,7 +188,7 @@ def save_posts_to_json(self, url: str, n_posts: int, verbose: bool) -> None:
186188
data = [self.get_post_data(content, i, verbose) for i in range(1, n_posts + 1)]
187189
self.write_to_json(url, data)
188190

189-
def write_to_json(self, url: str, data: List[Post]) -> None:
191+
def write_to_json(self, url: str, data: list[Post]) -> None:
190192
try:
191193
if url not in self.files_names:
192194
raise ValueError(f"No filename associated with url: {url}")

pyproject.toml

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,17 @@ ignore-words-list = "bu,collets,diamon,dout,empy,extint,fram,inh,minite,ned,parm
44
skip = "ARCHIVED/*,LICENSE,*.ai,*.pdf,*.svg"
55

66
[tool.ruff]
7-
target-version = "py310"
7+
target-version = "py38"
88
line-length = 127
9-
lint.extend-select = [
9+
lint.select = [
1010
# "C4", # flake8-comprehensions
11+
"E", # pycodestyle
12+
"F", # pyflakes
1113
"FURB", # refurb
1214
"I", # isort
1315
# "PERF", # Perflint
1416
"Q003", # avoidable-escaped-quote
15-
"UP031", # printf-string-formatting
16-
"UP032", # f-string
17-
# "UP", # pyupgradde
17+
"UP", # pyupgrade
18+
"W", # pycodestyle
1819
]
20+
lint.future-annotations = true

scripts/build_motor_diagrams.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ def load_json(file_path):
108108
load a json file and return the contents as a dict
109109
"""
110110
try:
111-
with open(file_path, "r") as file:
111+
with open(file_path) as file:
112112
return json.load(file)
113113
except (FileNotFoundError, json.JSONDecodeError) as e:
114114
print(f"Motor Diagrams: load_json() error\n{e}", file=stderr)

scripts/cap_params.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
for f in args.files:
1616
print(f"Processing {f}")
17-
txt = open(f, 'r').read()
17+
txt = open(f).read()
1818
matches = re.findall(r'[,.\s][A-Z][A-Z0-9]+_[A-Z_]+[,.\s]', txt)
1919
matches = re.findall(r'[,.\s][A-Z]+_[A-Z_]+[,.\s]', txt)
2020
changed = False

scripts/rename_params.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@
2323
args = parser.parse_args()
2424

2525

26-
def load_param_map(fname):
27-
lines = open(fname, 'r').readlines()
26+
def load_param_map(fname) -> dict:
27+
lines = open(fname).readlines()
2828
ret = {}
2929
for line in lines:
3030
if line.startswith("#"):
@@ -46,7 +46,7 @@ def process_file(fname, param_map):
4646
print(f"Skipping common file {fname}")
4747
return
4848
needs_write = False
49-
txt = open(fname, "r").read()
49+
txt = open(fname).read()
5050

5151
replacements = [":ref:`PARAMNAME <PARAMNAME>`",
5252
":ref:`PARAMNAME<PARAMNAME>`"]
@@ -68,7 +68,7 @@ def process_file(fname, param_map):
6868

6969

7070
param_map = load_param_map(args.param_map)
71-
print(f"Loaded param map for {len(param_map.keys())} parameters")
71+
print(f"Loaded param map for {len(param_map)} parameters")
7272

7373
for fname in args.files:
7474
if os.path.isfile(fname):

update.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
Parameters files are fetched from autotest using requests
3232
3333
"""
34+
from __future__ import annotations
3435

3536
import argparse
3637
import errno
@@ -49,7 +50,6 @@
4950
import time
5051
from concurrent.futures import ThreadPoolExecutor
5152
from datetime import datetime
52-
from typing import Dict, List, Optional
5353
from urllib.parse import urlparse
5454

5555
import requests
@@ -58,7 +58,7 @@
5858
import rst_table
5959
from frontend.scripts import get_discourse_posts
6060

61-
if sys.version_info < (3, 8):
61+
if sys.version_info < (3, 8): # noqa: UP036
6262
print("Minimum python version is 3.8")
6363
sys.exit(1)
6464

@@ -149,7 +149,7 @@ def fetch_and_rename(fetchurl: str, target_file: str, new_name: str) -> None:
149149
os.replace(new_name, target_file)
150150

151151

152-
def fetch_url(fetchurl: str, fpath: Optional[str] = None, verbose: bool = True) -> None:
152+
def fetch_url(fetchurl: str, fpath: str | None = None, verbose: bool = True) -> None:
153153
"""Fetches content at url and puts it in a file corresponding to the filename in the URL"""
154154
progress(f"Fetching {fetchurl}")
155155

@@ -192,7 +192,7 @@ def get_request_file_size(url: str) -> int:
192192
return 0
193193

194194

195-
def fetchparameters(site: Optional[str] = None, cache: Optional[str] = None) -> None:
195+
def fetchparameters(site: str | None = None, cache: str | None = None) -> None:
196196
dataname = "Parameters"
197197
fetch_ardupilot_generated_data(
198198
PARAMETER_SITE,
@@ -204,7 +204,7 @@ def fetchparameters(site: Optional[str] = None, cache: Optional[str] = None) ->
204204
)
205205

206206

207-
def fetchlogmessages(site: Optional[str] = None, cache: Optional[str] = None) -> None:
207+
def fetchlogmessages(site: str | None = None, cache: str | None = None) -> None:
208208
dataname = "LogMessages"
209209
fetch_ardupilot_generated_data(
210210
LOGMESSAGE_SITE,
@@ -216,18 +216,18 @@ def fetchlogmessages(site: Optional[str] = None, cache: Optional[str] = None) ->
216216
)
217217

218218

219-
def fetch_ardupilot_generated_data(site_mapping: Dict, base_url: str, sub_url: str, document_name: str,
220-
site: Optional[str] = None, cache: Optional[str] = None) -> None:
219+
def fetch_ardupilot_generated_data(site_mapping: dict, base_url: str, sub_url: str, document_name: str,
220+
site: str | None = None, cache: str | None = None) -> None:
221221
"""Fetches the data for all the sites from the test server and
222222
copies them to the correct location.
223223
224224
This is always run as part of a build (i.e. no checking to see if
225225
parameters or logmessage have changed.)
226226
227227
"""
228-
urls: List[str] = []
229-
targetfiles: List[str] = []
230-
names: List[str] = []
228+
urls: list[str] = []
229+
targetfiles: list[str] = []
230+
names: list[str] = []
231231

232232
for key, value in site_mapping.items():
233233
fetchurl = f'{base_url}/{value}/{sub_url}'
@@ -444,7 +444,7 @@ def copy_common_source_files(start_dir=COMMON_DIR, clean_common=False):
444444
for file in files:
445445
if file.endswith(".rst"):
446446
source_file_path = os.path.join(root, file)
447-
with open(source_file_path, 'r', encoding='utf-8') as f:
447+
with open(source_file_path, encoding='utf-8') as f:
448448
source_content = f.read()
449449
targets = get_copy_targets(source_content)
450450
for wiki in targets:
@@ -478,7 +478,7 @@ def copy_common_source_files(start_dir=COMMON_DIR, clean_common=False):
478478
if file.endswith(".rst"):
479479
# debug(" FILE: %s" % file)
480480
source_file_path = os.path.join(root, file)
481-
source_file = open(source_file_path, 'r', encoding='utf-8')
481+
source_file = open(source_file_path, encoding='utf-8')
482482
source_content = source_file.read()
483483
source_file.close()
484484
targets = get_copy_targets(source_content)
@@ -511,7 +511,7 @@ def copy_common_source_files(start_dir=COMMON_DIR, clean_common=False):
511511
shutil.copy2(src, dst)
512512
elif file.endswith(".js"):
513513
source_file_path = os.path.join(root, file)
514-
source_file = open(source_file_path, 'r', encoding='utf-8')
514+
source_file = open(source_file_path, encoding='utf-8')
515515
source_content = source_file.read()
516516
source_file.close()
517517
targets = get_copy_targets(source_content)
@@ -842,7 +842,7 @@ def check_ref_directives():
842842
wiki_glob = set(glob.glob("**/*.rst", recursive=True))
843843
files_to_check = wiki_glob.difference(skipped_files)
844844
for f in files_to_check:
845-
with open(f, "r", encoding='utf-8') as file:
845+
with open(f, encoding='utf-8') as file:
846846
try:
847847
for i, line in enumerate(file.readlines()):
848848
if character_before_ref_tag.search(line):

0 commit comments

Comments
 (0)