Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 2e410ba

Browse files
committedMay 16, 2025·
change to ruff
1 parent 3440b39 commit 2e410ba

12 files changed

+159
-494
lines changed
 

‎.gitattributes

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: Unlicense
4+
5+
.py text eol=lf
6+
.rst text eol=lf
7+
.txt text eol=lf
8+
.yaml text eol=lf
9+
.toml text eol=lf
10+
.license text eol=lf
11+
.md text eol=lf

‎.pre-commit-config.yaml

Lines changed: 11 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,21 @@
1-
# SPDX-FileCopyrightText: 2020 Diego Elio Pettenò
1+
# SPDX-FileCopyrightText: 2024 Justin Myers for Adafruit Industries
22
#
33
# SPDX-License-Identifier: Unlicense
44

55
repos:
6-
- repo: https://github.com/python/black
7-
rev: 23.3.0
8-
hooks:
9-
- id: black
10-
- repo: https://github.com/fsfe/reuse-tool
11-
rev: v1.1.2
12-
hooks:
13-
- id: reuse
146
- repo: https://github.com/pre-commit/pre-commit-hooks
15-
rev: v4.4.0
7+
rev: v4.5.0
168
hooks:
179
- id: check-yaml
1810
- id: end-of-file-fixer
1911
- id: trailing-whitespace
20-
- repo: https://github.com/pycqa/pylint
21-
rev: v2.17.4
12+
- repo: https://github.com/astral-sh/ruff-pre-commit
13+
rev: v0.3.4
2214
hooks:
23-
- id: pylint
24-
name: pylint (library code)
25-
types: [python]
26-
args:
27-
- --disable=consider-using-f-string
28-
exclude: "^(docs/|examples/|tests/|setup.py$)"
29-
- id: pylint
30-
name: pylint (example code)
31-
description: Run pylint rules on "examples/*.py" files
32-
types: [python]
33-
files: "^examples/"
34-
args:
35-
- --disable=missing-docstring,invalid-name,consider-using-f-string,duplicate-code
36-
- id: pylint
37-
name: pylint (test code)
38-
description: Run pylint rules on "tests/*.py" files
39-
types: [python]
40-
files: "^tests/"
41-
args:
42-
- --disable=missing-docstring,consider-using-f-string,duplicate-code
15+
- id: ruff-format
16+
- id: ruff
17+
args: ["--fix"]
18+
- repo: https://github.com/fsfe/reuse-tool
19+
rev: v3.0.1
20+
hooks:
21+
- id: reuse

‎.pylintrc

Lines changed: 0 additions & 399 deletions
This file was deleted.

‎README.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,9 @@ Introduction
1313
:target: https://github.com/adafruit/Adafruit_CircuitPython_Logger
1414
:alt: Build Status
1515

16-
.. image:: https://img.shields.io/badge/code%20style-black-000000.svg
17-
:target: https://github.com/psf/black
18-
:alt: Code Style: Black
16+
.. image:: https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json
17+
:target: https://github.com/astral-sh/ruff
18+
:alt: Code Style: Ruff
1919

2020
Logging module for CircuitPython
2121

‎adafruit_logging.py

Lines changed: 17 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -55,16 +55,14 @@
5555
5656
"""
5757

58-
# pylint: disable=invalid-name,undefined-variable
59-
60-
import time
61-
import sys
6258
import os
59+
import sys
60+
import time
6361
from collections import namedtuple
6462

6563
try:
66-
# pylint: disable=deprecated-class
67-
from typing import Optional, Hashable, Dict
64+
from typing import Dict, Hashable, Optional
65+
6866
from typing_extensions import Protocol
6967

7068
class WriteableStream(Protocol):
@@ -82,7 +80,6 @@ def write(self, buf: str) -> int:
8280
__version__ = "0.0.0+auto.0"
8381
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_Logger.git"
8482

85-
# pylint:disable=undefined-all-variable
8683
__all__ = [
8784
"LEVELS",
8885
"NOTSET",
@@ -129,9 +126,7 @@ def _level_for(value: int) -> str:
129126
return LEVELS[0][1]
130127

131128

132-
LogRecord = namedtuple(
133-
"_LogRecord", ("name", "levelno", "levelname", "msg", "created", "args")
134-
)
129+
LogRecord = namedtuple("_LogRecord", ("name", "levelno", "levelname", "msg", "created", "args"))
135130
"""An object used to hold the contents of a log record. The following attributes can
136131
be retrieved from it:
137132
@@ -163,7 +158,7 @@ class Formatter:
163158
style is '{'
164159
"""
165160

166-
def __init__( # pylint: disable=too-many-arguments
161+
def __init__(
167162
self,
168163
fmt: Optional[str] = None,
169164
datefmt: Optional[str] = None,
@@ -174,10 +169,8 @@ def __init__( # pylint: disable=too-many-arguments
174169
self.fmt = fmt
175170
self.datefmt = datefmt
176171
self.style = style
177-
if self.style not in ("{", "%"):
178-
raise ValueError(
179-
"Only '%' and '{' formatting style are supported at this time."
180-
)
172+
if self.style not in {"{", "%"}:
173+
raise ValueError("Only '%' and '{' formatting style are supported at this time.")
181174

182175
self.validate = validate
183176
self.defaults = defaults
@@ -199,20 +192,17 @@ def format(self, record: LogRecord) -> str:
199192
}
200193
if "{asctime}" in self.fmt or "%(asctime)s" in self.fmt:
201194
now = time.localtime()
202-
# pylint: disable=line-too-long
203-
vals[
204-
"asctime"
205-
] = f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}"
195+
vals["asctime"] = (
196+
f"{now.tm_year}-{now.tm_mon:02d}-{now.tm_mday:02d} {now.tm_hour:02d}:{now.tm_min:02d}:{now.tm_sec:02d}" # noqa: E501
197+
)
206198

207199
if self.defaults:
208200
for key, val in self.defaults.items():
209201
if key not in vals:
210202
vals[key] = val
211203

212-
if self.style not in ("{", "%"):
213-
raise ValueError(
214-
"Only '%' and '{' formatting style are supported at this time."
215-
)
204+
if self.style not in {"{", "%"}:
205+
raise ValueError("Only '%' and '{' formatting style are supported at this time.")
216206

217207
if self.style == "%":
218208
return self.fmt % vals
@@ -234,7 +224,6 @@ def setLevel(self, level: int) -> None:
234224
"""
235225
self.level = level
236226

237-
# pylint: disable=no-self-use
238227
def format(self, record: LogRecord) -> str:
239228
"""Generate a timestamped message.
240229
@@ -263,7 +252,6 @@ def setFormatter(self, formatter: Formatter) -> None:
263252
self.formatter = formatter
264253

265254

266-
# pylint: disable=too-few-public-methods
267255
class StreamHandler(Handler):
268256
"""Send logging messages to a stream, `sys.stderr` (typically
269257
the serial console) by default.
@@ -316,7 +304,6 @@ class FileHandler(StreamHandler):
316304
terminator = "\r\n"
317305

318306
def __init__(self, filename: str, mode: str = "a") -> None:
319-
# pylint: disable=consider-using-with
320307
if mode == "r":
321308
raise ValueError("Can't write to a read only file")
322309
super().__init__(open(filename, mode=mode))
@@ -404,7 +391,6 @@ def doRollover(self) -> None:
404391
os.rename(self._LogFileName, CurrentFileName)
405392

406393
# Reopen the file.
407-
# pylint: disable=consider-using-with
408394
self.stream = open(self._LogFileName, mode=self._WriteMode)
409395

410396
def GetLogSize(self) -> int:
@@ -522,24 +508,16 @@ def hasHandlers(self) -> bool:
522508
return len(self._handlers) > 0
523509

524510
def _log(self, level: int, msg: str, *args) -> None:
525-
record = _logRecordFactory(
526-
self.name, level, (msg % args) if args else msg, args
527-
)
511+
record = _logRecordFactory(self.name, level, (msg % args) if args else msg, args)
528512
self.handle(record)
529513

530514
def handle(self, record: LogRecord) -> None:
531515
"""Pass the record to all handlers registered with this logger.
532516
533517
:param LogRecord record: log record
534518
"""
535-
if (
536-
_default_handler is None
537-
and not self.hasHandlers()
538-
and not self.emittedNoHandlerWarning
539-
):
540-
sys.stderr.write(
541-
f"Logger '{self.name}' has no handlers and default handler is None\n"
542-
)
519+
if _default_handler is None and not self.hasHandlers() and not self.emittedNoHandlerWarning:
520+
sys.stderr.write(f"Logger '{self.name}' has no handlers and default handler is None\n")
543521
self.emittedNoHandlerWarning = True
544522
return
545523

@@ -550,11 +528,7 @@ def handle(self, record: LogRecord) -> None:
550528
handler.emit(record)
551529
emitted = True
552530

553-
if (
554-
not emitted
555-
and _default_handler
556-
and record.levelno >= _default_handler.level
557-
):
531+
if not emitted and _default_handler and record.levelno >= _default_handler.level:
558532
_default_handler.emit(record)
559533

560534
def log(self, level: int, msg: str, *args) -> None:
@@ -622,14 +596,12 @@ def critical(self, msg: str, *args) -> None:
622596
"""
623597
self._log(CRITICAL, msg, *args)
624598

625-
# pylint: disable=no-value-for-parameter; value and tb are optional for traceback
626599
def exception(self, err: Exception) -> None:
627600
"""Convenience method for logging an ERROR with exception information.
628601
629602
:param Exception err: the exception to be logged
630603
"""
631604
try:
632-
# pylint: disable=import-outside-toplevel; not available on all boards
633605
import traceback
634606
except ImportError:
635607
self._log(

‎docs/api.rst

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,8 @@
44
.. If your library file(s) are nested in a directory (e.g. /adafruit_foo/foo.py)
55
.. use this format as the module name: "adafruit_foo.foo"
66
7+
API Reference
8+
#############
9+
710
.. automodule:: adafruit_logging
811
:members:

‎docs/conf.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
1-
# -*- coding: utf-8 -*-
2-
31
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
42
#
53
# SPDX-License-Identifier: MIT
64

5+
import datetime
76
import os
87
import sys
9-
import datetime
108

119
sys.path.insert(0, os.path.abspath(".."))
1210

@@ -48,9 +46,7 @@
4846
creation_year = "2019"
4947
current_year = str(datetime.datetime.now().year)
5048
year_duration = (
51-
current_year
52-
if current_year == creation_year
53-
else creation_year + " - " + current_year
49+
current_year if current_year == creation_year else creation_year + " - " + current_year
5450
)
5551
copyright = year_duration + " Dave Astels"
5652
author = "Dave Astels"

‎examples/logging_filehandler.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
# SPDX-FileCopyrightText: 2021 Alec Delaney
22
# SPDX-License-Identifier: MIT
33

4+
import adafruit_sdcard
45
import board
56
import busio
6-
from digitalio import DigitalInOut
77
import storage
8-
import adafruit_sdcard
8+
from digitalio import DigitalInOut
9+
910
import adafruit_logging as logging
1011
from adafruit_logging import FileHandler
1112

‎examples/logging_formatter_example.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,7 @@
3434
logger.info("Custom formatter example")
3535

3636

37-
bracket_timestamp_formatter = logging.Formatter(
38-
fmt="{asctime} {levelname}: {message}", style="{"
39-
)
37+
bracket_timestamp_formatter = logging.Formatter(fmt="{asctime} {levelname}: {message}", style="{")
4038
print_handler.setFormatter(bracket_timestamp_formatter)
4139
logger.info("Timestamp formatter bracket style example")
4240

‎examples/logging_mqtt_handler.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import adafruit_logging as logging
1515

1616
# adafruit_logging defines log levels dynamically.
17-
# pylint: disable=no-name-in-module
1817
from adafruit_logging import NOTSET, Handler, LogRecord
1918

2019

‎examples/logging_simpletest.py

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
22
# SPDX-License-Identifier: MIT
33

4-
# pylint:disable=undefined-variable,wildcard-import,no-name-in-module
5-
# pylint:disable=no-member,invalid-name
6-
74
"""Briefly exercise the logger and null logger."""
85

96
import adafruit_logging as logging

‎ruff.toml

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
# SPDX-FileCopyrightText: 2024 Tim Cocks for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
target-version = "py38"
6+
line-length = 100
7+
8+
[lint]
9+
preview = true
10+
select = ["I", "PL", "UP"]
11+
12+
extend-select = [
13+
"D419", # empty-docstring
14+
"E501", # line-too-long
15+
"W291", # trailing-whitespace
16+
"PLC0414", # useless-import-alias
17+
"PLC2401", # non-ascii-name
18+
"PLC2801", # unnecessary-dunder-call
19+
"PLC3002", # unnecessary-direct-lambda-call
20+
"E999", # syntax-error
21+
"PLE0101", # return-in-init
22+
"F706", # return-outside-function
23+
"F704", # yield-outside-function
24+
"PLE0116", # continue-in-finally
25+
"PLE0117", # nonlocal-without-binding
26+
"PLE0241", # duplicate-bases
27+
"PLE0302", # unexpected-special-method-signature
28+
"PLE0604", # invalid-all-object
29+
"PLE0605", # invalid-all-format
30+
"PLE0643", # potential-index-error
31+
"PLE0704", # misplaced-bare-raise
32+
"PLE1141", # dict-iter-missing-items
33+
"PLE1142", # await-outside-async
34+
"PLE1205", # logging-too-many-args
35+
"PLE1206", # logging-too-few-args
36+
"PLE1307", # bad-string-format-type
37+
"PLE1310", # bad-str-strip-call
38+
"PLE1507", # invalid-envvar-value
39+
"PLE2502", # bidirectional-unicode
40+
"PLE2510", # invalid-character-backspace
41+
"PLE2512", # invalid-character-sub
42+
"PLE2513", # invalid-character-esc
43+
"PLE2514", # invalid-character-nul
44+
"PLE2515", # invalid-character-zero-width-space
45+
"PLR0124", # comparison-with-itself
46+
"PLR0202", # no-classmethod-decorator
47+
"PLR0203", # no-staticmethod-decorator
48+
"UP004", # useless-object-inheritance
49+
"PLR0206", # property-with-parameters
50+
"PLR0904", # too-many-public-methods
51+
"PLR0911", # too-many-return-statements
52+
"PLR0912", # too-many-branches
53+
"PLR0913", # too-many-arguments
54+
"PLR0914", # too-many-locals
55+
"PLR0915", # too-many-statements
56+
"PLR0916", # too-many-boolean-expressions
57+
"PLR1702", # too-many-nested-blocks
58+
"PLR1704", # redefined-argument-from-local
59+
"PLR1711", # useless-return
60+
"C416", # unnecessary-comprehension
61+
"PLR1733", # unnecessary-dict-index-lookup
62+
"PLR1736", # unnecessary-list-index-lookup
63+
64+
# ruff reports this rule is unstable
65+
#"PLR6301", # no-self-use
66+
67+
"PLW0108", # unnecessary-lambda
68+
"PLW0120", # useless-else-on-loop
69+
"PLW0127", # self-assigning-variable
70+
"PLW0129", # assert-on-string-literal
71+
"B033", # duplicate-value
72+
"PLW0131", # named-expr-without-context
73+
"PLW0245", # super-without-brackets
74+
"PLW0406", # import-self
75+
"PLW0602", # global-variable-not-assigned
76+
"PLW0603", # global-statement
77+
"PLW0604", # global-at-module-level
78+
79+
# fails on the try: import typing used by libraries
80+
#"F401", # unused-import
81+
82+
"F841", # unused-variable
83+
"E722", # bare-except
84+
"PLW0711", # binary-op-exception
85+
"PLW1501", # bad-open-mode
86+
"PLW1508", # invalid-envvar-default
87+
"PLW1509", # subprocess-popen-preexec-fn
88+
"PLW2101", # useless-with-lock
89+
"PLW3301", # nested-min-max
90+
]
91+
92+
ignore = [
93+
"PLR2004", # magic-value-comparison
94+
"UP030", # format literals
95+
"PLW1514", # unspecified-encoding
96+
"PLR0913", # too-many-arguments
97+
"PLR0915", # too-many-statements
98+
"PLR0917", # too-many-positional-arguments
99+
"PLR0904", # too-many-public-methods
100+
"PLR0912", # too-many-branches
101+
"PLR0916", # too-many-boolean-expressions
102+
"PLR6301", # could-be-static no-self-use
103+
"PLC0415", # import outside toplevel
104+
"PLC2701", # private import
105+
]
106+
107+
[format]
108+
line-ending = "lf"

0 commit comments

Comments
 (0)
Please sign in to comment.