Skip to content

Commit 4da6e6f

Browse files
committed
all: Lint Python code with ruff.
Signed-off-by: Christian Clauss <[email protected]>
1 parent 752ce66 commit 4da6e6f

File tree

24 files changed

+139
-46
lines changed

24 files changed

+139
-46
lines changed

.github/workflows/build_packages.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ jobs:
99
build:
1010
runs-on: ubuntu-latest
1111
steps:
12-
- uses: actions/checkout@v2
13-
- uses: actions/setup-python@v1
12+
- uses: actions/checkout@v3
13+
- uses: actions/setup-python@v4
1414
- name: Setup environment
1515
run: source tools/ci.sh && ci_build_packages_setup
1616
- name: Check manifest files

.github/workflows/cleanup_published_packages.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@ jobs:
77
runs-on: ubuntu-latest
88
if: vars.MICROPY_PUBLISH_MIP_INDEX
99
steps:
10-
- uses: actions/checkout@v2
10+
- uses: actions/checkout@v3
1111
- name: Clean up published files
1212
run: source tools/ci.sh && ci_cleanup_package_index ${{ github.event.ref }}

.github/workflows/code_formatting.yml

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,10 @@ jobs:
66
build:
77
runs-on: ubuntu-latest
88
steps:
9-
- uses: actions/checkout@v2
10-
- uses: actions/setup-python@v1
9+
- uses: actions/checkout@v3
10+
- run: pip install --user ruff
11+
- run: ruff --format=github .
12+
- uses: actions/setup-python@v4
1113
- name: Install packages
1214
run: source tools/ci.sh && ci_code_formatting_setup
1315
- name: Run code formatting

micropython/aioespnow/aioespnow.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,17 +11,17 @@ class AIOESPNow(espnow.ESPNow):
1111
# Read one ESPNow message
1212
async def arecv(self):
1313
yield asyncio.core._io_queue.queue_read(self)
14-
return self.recv(0) # type: ignore
14+
return self.recv(0) # type: ignore[misc]
1515

1616
async def airecv(self):
1717
yield asyncio.core._io_queue.queue_read(self)
18-
return self.irecv(0) # type: ignore
18+
return self.irecv(0) # type: ignore[misc]
1919

2020
async def asend(self, mac, msg=None, sync=None):
2121
if msg is None:
2222
msg, mac = mac, None # If msg is None: swap mac and msg
2323
yield asyncio.core._io_queue.queue_write(self)
24-
return self.send(mac, msg, sync) # type: ignore
24+
return self.send(mac, msg, sync) # type: ignore[misc]
2525

2626
# "async for" support
2727
def __aiter__(self):

micropython/bluetooth/aioble/examples/l2cap_file_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ async def download(self, path, dest):
8787

8888
send_seq = await self._command(_COMMAND_SEND, path.encode())
8989

90-
with open(dest, "wb") as f:
90+
with open(dest, "wb") as f: # noqa: ASYNC101
9191
total = 0
9292
buf = bytearray(self._channel.our_mtu)
9393
mv = memoryview(buf)

micropython/bluetooth/aioble/examples/l2cap_file_server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ async def l2cap_task(connection):
8282

8383
if send_file:
8484
print("Sending:", send_file)
85-
with open(send_file, "rb") as f:
85+
with open(send_file, "rb") as f: # noqa: ASYNC101
8686
buf = bytearray(channel.peer_mtu)
8787
mv = memoryview(buf)
8888
while n := f.readinto(buf):

micropython/drivers/codec/wm8960/wm8960.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -578,7 +578,7 @@ def set_data_route(self, route):
578578
raise ValueError("Invalid route")
579579

580580
def set_left_input(self, input):
581-
if not input in self._input_config_table.keys():
581+
if input not in self._input_config_table:
582582
raise ValueError("Invalid input")
583583

584584
input = self._input_config_table[input]
@@ -595,7 +595,7 @@ def set_left_input(self, input):
595595
regs[_LINVOL] = input[1]
596596

597597
def set_right_input(self, input):
598-
if not input in self._input_config_table.keys():
598+
if input not in self._input_config_table:
599599
raise ValueError("Invalid input name")
600600

601601
input = self._input_config_table[input]
@@ -629,7 +629,7 @@ def config_data_format(self, sysclk, sample_rate, bits):
629629
self.regs[_IFACE1] = (_IFACE1_WL_MASK, wl << _IFACE1_WL_SHIFT)
630630

631631
def volume(self, module, volume_l=None, volume_r=None):
632-
if not module in self._volume_config_table.keys():
632+
if module not in self._volume_config_table:
633633
raise ValueError("Invalid module")
634634

635635
if volume_l is None: # get volume
@@ -644,7 +644,7 @@ def volume(self, module, volume_l=None, volume_r=None):
644644

645645
if not ((0 <= volume_l <= 100) and (0 <= volume_r <= 100)):
646646
raise ValueError("Invalid value for volume")
647-
elif not module in self._volume_config_table.keys():
647+
elif module not in self._volume_config_table:
648648
raise ValueError("Invalid module")
649649

650650
vol_max, regnum, flags = self._volume_config_table[module]

micropython/drivers/imu/bmi270/bmi270.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -524,13 +524,13 @@ def __init__(
524524
# Sanity checks
525525
if not self._use_i2c:
526526
raise ValueError("SPI mode is not supported")
527-
if not gyro_odr in ODR:
527+
if gyro_odr not in ODR:
528528
raise ValueError("Invalid gyro sampling rate: %d" % gyro_odr)
529-
if not gyro_scale in GYRO_SCALE:
529+
if gyro_scale not in GYRO_SCALE:
530530
raise ValueError("Invalid gyro scaling: %d" % gyro_scale)
531-
if not accel_odr in ODR:
531+
if accel_odr not in ODR:
532532
raise ValueError("Invalid accelerometer sampling rate: %d" % accel_odr)
533-
if not accel_scale in ACCEL_SCALE:
533+
if accel_scale not in ACCEL_SCALE:
534534
raise ValueError("Invalid accelerometer scaling: %d" % accel_scale)
535535
if self._read_reg(_CHIP_ID) != 0x24:
536536
raise OSError("No BMI270 device was found at address 0x%x" % (self.address))

micropython/drivers/imu/bmm150/bmm150.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def __init__(
8080
# Sanity checks
8181
if not self._use_i2c:
8282
raise ValueError("SPI mode is not supported")
83-
if not magnet_odr in _ODR:
83+
if magnet_odr not in _ODR:
8484
raise ValueError("Invalid sampling rate: %d" % magnet_odr)
8585

8686
# Perform soft reset, and power on.

micropython/drivers/imu/lsm6dsox/lsm6dsox.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -130,20 +130,20 @@ def __init__(
130130
accel_odr = round(accel_odr, 2)
131131

132132
# Sanity checks
133-
if not gyro_odr in ODR:
133+
if gyro_odr not in ODR:
134134
raise ValueError("Invalid sampling rate: %d" % gyro_odr)
135-
if not gyro_scale in SCALE_GYRO:
135+
if gyro_scale not in SCALE_GYRO:
136136
raise ValueError("invalid gyro scaling: %d" % gyro_scale)
137-
if not accel_odr in ODR:
137+
if accel_odr not in ODR:
138138
raise ValueError("Invalid sampling rate: %d" % accel_odr)
139-
if not accel_scale in SCALE_ACCEL:
139+
if accel_scale not in SCALE_ACCEL:
140140
raise ValueError("invalid accelerometer scaling: %d" % accel_scale)
141141

142142
# Soft-reset the device.
143143
self.reset()
144144

145145
# Load and configure MLC if UCF file is provided
146-
if ucf != None:
146+
if ucf is not None:
147147
self.load_mlc(ucf)
148148

149149
# Set Gyroscope datarate and scale.

micropython/drivers/imu/lsm6dsox/lsm6dsox_mlc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ def imu_int_handler(pin):
1717
INT_FLAG = True
1818

1919

20-
if INT_MODE == True:
20+
if INT_MODE is True:
2121
int_pin = Pin(24)
2222
int_pin.irq(handler=imu_int_handler, trigger=Pin.IRQ_RISING)
2323

@@ -44,5 +44,5 @@ def imu_int_handler(pin):
4444
print(UCF_LABELS[lsm.mlc_output()[0]])
4545
else:
4646
buf = lsm.mlc_output()
47-
if buf != None:
47+
if buf is not None:
4848
print(UCF_LABELS[buf[0]])

micropython/drivers/imu/lsm9ds1/lsm9ds1.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,19 +95,19 @@ def __init__(
9595
self.address_magnet = address_magnet
9696

9797
# Sanity checks
98-
if not gyro_odr in _ODR_IMU:
98+
if gyro_odr not in _ODR_IMU:
9999
raise ValueError("Invalid gyro sampling rate: %d" % gyro_odr)
100-
if not gyro_scale in _GYRO_SCALE:
100+
if gyro_scale not in _GYRO_SCALE:
101101
raise ValueError("Invalid gyro scaling: %d" % gyro_scale)
102102

103-
if not accel_odr in _ODR_IMU:
103+
if accel_odr not in _ODR_IMU:
104104
raise ValueError("Invalid accelerometer sampling rate: %d" % accel_odr)
105-
if not accel_scale in _ACCEL_SCALE:
105+
if accel_scale not in _ACCEL_SCALE:
106106
raise ValueError("Invalid accelerometer scaling: %d" % accel_scale)
107107

108-
if not magnet_odr in _ODR_MAGNET:
108+
if magnet_odr not in _ODR_MAGNET:
109109
raise ValueError("Invalid magnet sampling rate: %d" % magnet_odr)
110-
if not magnet_scale in _MAGNET_SCALE:
110+
if magnet_scale not in _MAGNET_SCALE:
111111
raise ValueError("Invalid magnet scaling: %d" % magnet_scale)
112112

113113
if (self.magent_id() != b"=") or (self.gyro_id() != b"h"):

micropython/lora/examples/simple_rxtx/simple_rxtx.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ def main():
4040
print("Receiving...")
4141
rx = modem.recv(timeout_ms=5000)
4242
if rx:
43-
print(f"Received: {repr(rx)}")
43+
print(f"Received: {rx!r}")
4444
else:
4545
print("Timeout!")
4646
time.sleep(2)

micropython/lora/examples/simple_rxtx/simple_rxtx_async.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ async def recv_coro(modem):
4141
print("Receiving...")
4242
rx = await modem.recv(2000)
4343
if rx:
44-
print(f"Received: {repr(rx)}")
44+
print(f"Received: {rx!r}")
4545
else:
4646
print("Receive timeout!")
4747

micropython/lora/lora-sx126x/lora/sx126x.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -487,7 +487,7 @@ def calibrate_image(self):
487487
else:
488488
# DS says "Contact your Semtech representative for the other optimal
489489
# calibration settings outside of the given frequency bands"
490-
raise ValueError()
490+
raise ValueError
491491

492492
self._cmd(">BH", _CMD_CALIBRATE_IMAGE, args)
493493

micropython/lora/lora/lora/modem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -282,7 +282,7 @@ def start_recv(self, timeout_ms=None, continuous=False, rx_length=0xFF):
282282
#
283283
# Part of common low-level modem API, see README.md for usage.
284284
if continuous and timeout_ms is not None:
285-
raise ValueError() # these two options are mutually exclusive
285+
raise ValueError # these two options are mutually exclusive
286286

287287
if timeout_ms is not None:
288288
self._rx = time.ticks_add(time.ticks_ms(), timeout_ms)

micropython/senml/examples/custom_record.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def __init__(self, name, **kwargs):
4343

4444
def _check_value_type(self, value):
4545
"""overriding the check on value type to make certain that only an array with 3 values is assigned: lat,lon/alt"""
46-
if not value == None:
46+
if value is not None:
4747
if not isinstance(value, list):
4848
raise Exception("invalid data type: array with 3 elements expected lat, lon, alt")
4949

micropython/senml/examples/gateway_actuators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ def gateway_callback(record, **kwargs):
5656
:param kwargs: optional extra parameters (device can be found here)
5757
:return: None
5858
"""
59-
if "device" in kwargs and kwargs["device"] != None:
59+
if "device" in kwargs and kwargs["device"] is not None:
6060
print("for device: " + kwargs["device"].name)
6161
else:
6262
print("for gateway: ")

micropython/senml/senml/senml_pack.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def __next__(self):
4747
self._index += 1
4848
return res
4949
else:
50-
raise StopIteration()
50+
raise StopIteration
5151

5252

5353
class SenmlPack(SenmlBase):
@@ -156,7 +156,7 @@ def _check_value_type(self, value, field_name):
156156
checks if the type of value is allowed for senml
157157
:return: None, raisee exception if not ok.
158158
"""
159-
if not value == None:
159+
if value is not None:
160160
if not (isinstance(value, int) or isinstance(value, float)):
161161
raise Exception("invalid type for " + field_name + ", only numbers allowed")
162162

@@ -330,7 +330,7 @@ def add(self, item):
330330
"""
331331
if not (isinstance(item, SenmlBase)):
332332
raise Exception("invalid type of param, SenmlRecord or SenmlPack expected")
333-
if not item._parent == None:
333+
if item._parent is not None:
334334
raise Exception("item is already part of a pack")
335335

336336
self._data.append(item)

micropython/senml/senml/senml_record.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ def _check_value_type(self, value):
7979
checks if the type of value is allowed for senml
8080
:return: None, raisee exception if not ok.
8181
"""
82-
if not value == None:
82+
if value is not None:
8383
if not (
8484
isinstance(value, bool)
8585
or isinstance(value, int)
@@ -96,7 +96,7 @@ def _check_number_type(self, value, field_name):
9696
checks if the type of value is allowed for senml
9797
:return: None, raisee exception if not ok.
9898
"""
99-
if not value == None:
99+
if value is not None:
100100
if not (isinstance(value, int) or isinstance(value, float)):
101101
raise Exception("invalid type for " + field_name + ", only numbers allowed")
102102

pyproject.toml

Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
[tool.ruff]
2+
exclude = [
3+
"python-stdlib",
4+
"unix-ffi",
5+
]
6+
select = [
7+
"ASYNC", # flake8-comprehensions
8+
"C4", # flake8-comprehensions
9+
"C90", # McCabe cyclomatic complexity
10+
"DTZ", # flake8-datetimez
11+
"E", # pycodestyle
12+
"EXE", # flake8-executable
13+
"F", # Pyflakes
14+
"G", # flake8-logging-format
15+
"ICN", # flake8-import-conventions
16+
"INT", # flake8-gettext
17+
"ISC", # flake8-implicit-str-concat
18+
"PGH", # pygrep-hooks
19+
"PIE", # flake8-pie
20+
"PL", # Pylint
21+
"PYI", # flake8-pyi
22+
"RSE", # flake8-raise
23+
"RUF", # Ruff-specific rules
24+
"T10", # flake8-debugger
25+
"TCH", # flake8-type-checking
26+
"W", # pycodestyle
27+
"YTT", # flake8-2020
28+
# "A", # flake8-builtins
29+
# "ANN", # flake8-annotations
30+
# "ARG", # flake8-unused-arguments
31+
# "B", # flake8-bugbear
32+
# "BLE", # flake8-blind-except
33+
# "COM", # flake8-commas
34+
# "D", # pydocstyle
35+
# "DJ", # flake8-django
36+
# "EM", # flake8-errmsg
37+
# "ERA", # eradicate
38+
# "FBT", # flake8-boolean-trap
39+
# "I", # isort
40+
# "INP", # flake8-no-pep420
41+
# "N", # pep8-naming
42+
# "NPY", # NumPy-specific rules
43+
# "PD", # pandas-vet
44+
# "PT", # flake8-pytest-style
45+
# "PTH", # flake8-use-pathlib
46+
# "Q", # flake8-quotes
47+
# "RET", # flake8-return
48+
# "S", # flake8-bandit
49+
# "SIM", # flake8-simplify
50+
# "SLF", # flake8-self
51+
# "T20", # flake8-print
52+
# "TID", # flake8-tidy-imports
53+
# "TRY", # tryceratops
54+
# "UP", # pyupgrade
55+
]
56+
ignore = [
57+
"E401",
58+
"E402",
59+
"E722",
60+
"E741",
61+
"F401",
62+
"F403",
63+
"F405",
64+
"F541",
65+
"F821",
66+
"F841",
67+
"ISC003", # micropython does not support implicit concatenation of f-strings
68+
"PIE810", # micropython does not support passing tuples to .startswith or .endswith
69+
"PLC1901",
70+
"PLR1701",
71+
"PLR1714",
72+
"PLR5501",
73+
"PLW0602",
74+
"PLW0603",
75+
"PLW2901",
76+
"RUF012",
77+
"RUF100",
78+
]
79+
line-length = 260
80+
target-version = "py37"
81+
82+
[tool.ruff.mccabe]
83+
max-complexity = 61
84+
85+
[tool.ruff.pylint]
86+
allow-magic-value-types = ["bytes", "int", "str"]
87+
max-args = 14
88+
max-branches = 58
89+
max-returns = 13
90+
max-statements = 166
91+
92+
[tool.ruff.per-file-ignores]
93+
"micropython/aiorepl/aiorepl.py" = ["PGH001"]

0 commit comments

Comments
 (0)