all: Upgrade to ruff v0.9.6.

Signed-off-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Christian Clauss 2025-02-18 10:01:09 +01:00
parent 3f0dd13d93
commit dc2fcfcc55
54 changed files with 73 additions and 17 deletions

View file

@ -8,6 +8,6 @@ jobs:
steps:
- uses: actions/checkout@v4
# ruff version should be kept in sync with .pre-commit-config.yaml
- run: pip install --user ruff==0.1.3
- run: pipx install ruff==0.9.6
- run: ruff check --output-format=github .
- run: ruff format --diff .

View file

@ -13,7 +13,7 @@ repos:
stages: [commit-msg]
- repo: https://github.com/charliermarsh/ruff-pre-commit
# Version should be kept in sync with .github/workflows/ruff.yml
rev: v0.1.3
rev: v0.9.6
hooks:
- id: ruff
- id: ruff-format

View file

@ -44,6 +44,7 @@ Example usage of SD card reader:
tf = mount_tf()
os.listdir()
"""
import vfs
import time
import framebuf

View file

@ -27,6 +27,17 @@ line-length = 99
target-version = "py37"
[tool.ruff.lint]
exclude = [ # Ruff finds Python SyntaxError in these files
"tests/cmdline/repl_autocomplete.py",
"tests/cmdline/repl_autoindent.py",
"tests/cmdline/repl_basic.py",
"tests/cmdline/repl_cont.py",
"tests/cmdline/repl_emacs_keys.py",
"tests/cmdline/repl_words_move.py",
"tests/feature_check/repl_emacs_check.py",
"tests/feature_check/repl_words_move_check.py",
"tests/micropython/viper_args.py",
]
extend-select = ["C9", "PLC"]
ignore = [
"E401",
@ -37,14 +48,12 @@ ignore = [
"F401",
"F403",
"F405",
"PLC1901",
"PLC0206",
]
mccabe.max-complexity = 40
[tool.ruff.mccabe]
max-complexity = 40
[tool.ruff.per-file-ignores]
# Exclude all tests from linting (does not apply to formatting).
[tool.ruff.lint.per-file-ignores]
# Exclude all tests from linting.
"tests/**/*.py" = ["ALL"]
"ports/cc3200/tools/uniflash.py" = ["E711"]
# manifest.py files are evaluated with some global names pre-defined
@ -57,3 +66,4 @@ max-complexity = 40
# repl_: not real python files
# viper_args: uses f(*)
exclude = ["tests/basics/*.py", "tests/*/repl_*.py", "tests/micropython/viper_args.py"]
quote-style = "preserve"

View file

@ -9,4 +9,5 @@ workaround: Instead of ``val = next(it, deflt)`` use::
except StopIteration:
val = deflt
"""
print(next(iter(range(0)), 42))

View file

@ -4,6 +4,7 @@ description: Special method __del__ not implemented for user-defined classes
cause: Unknown
workaround: Unknown
"""
import gc

View file

@ -6,7 +6,9 @@ workaround: Use the + operator between literal strings when they are not both f-
"""
x, y = 1, 2
# fmt: off
print("aa" f"{x}") # works
print(f"{x}" "ab") # works
print("a{}a" f"{x}") # fails
print(f"{x}" "a{}b") # fails
# fmt: on

View file

@ -4,6 +4,7 @@ description: Error messages for methods may display unexpected argument counts
cause: MicroPython counts "self" as an argument.
workaround: Interpret error messages with the information above in mind.
"""
try:
[].append()
except Exception as e:

View file

@ -4,6 +4,7 @@ description: __all__ is unsupported in __init__.py in MicroPython.
cause: Not implemented.
workaround: Manually import the sub-modules directly in __init__.py using ``from . import foo, bar``.
"""
from modules3 import *
foo.hello()

View file

@ -4,6 +4,7 @@ description: __path__ attribute of a package has a different type (single string
cause: MicroPython doesn't support namespace packages split across filesystem. Beyond that, MicroPython's import system is highly optimized for minimal memory usage.
workaround: Details of import handling is inherently implementation dependent. Don't rely on such details in portable applications.
"""
import modules
print(modules.__path__)

View file

@ -4,6 +4,7 @@ description: MicroPython doesn't support namespace packages split across filesys
cause: MicroPython's import system is highly optimized for simplicity, minimal memory usage, and minimal filesystem search overhead.
workaround: Don't install modules belonging to the same namespace package in different directories. For MicroPython, it's recommended to have at most 3-component module search paths: for your current application, per-user (writable), system-wide (non-writable).
"""
import sys
sys.path.append(sys.path[1] + "/modules")

View file

@ -4,6 +4,7 @@ description: Code running in eval() function doesn't have access to local variab
cause: MicroPython doesn't maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can't be accessed by a name. Effectively, ``eval(expr)`` in MicroPython is equivalent to ``eval(expr, globals(), globals())``.
workaround: Unknown
"""
val = 1

View file

@ -4,6 +4,7 @@ description: Comparison between different typecodes not supported
cause: Code size
workaround: Compare individual elements
"""
import array
array.array("b", [1, 2]) == array.array("i", [1, 2])

View file

@ -4,6 +4,7 @@ description: Overflow checking is not implemented
cause: MicroPython implements implicit truncation in order to reduce code size and execution time
workaround: If CPython compatibility is needed then mask the value explicitly
"""
import array
a = array.array("b", [257])

View file

@ -4,6 +4,7 @@ description: Looking for integer not implemented
cause: Unknown
workaround: Unknown
"""
import array
print(1 in array.array("B", b"12"))

View file

@ -4,6 +4,7 @@ description: Array deletion not implemented
cause: Unknown
workaround: Unknown
"""
import array
a = array.array("b", (1, 2, 3))

View file

@ -4,6 +4,7 @@ description: Subscript with step != 1 is not yet implemented
cause: Unknown
workaround: Unknown
"""
import array
a = array.array("b", (1, 2, 3))

View file

@ -4,6 +4,7 @@ description: JSON module does not throw exception when object is not serialisabl
cause: Unknown
workaround: Unknown
"""
import json
try:

View file

@ -4,6 +4,7 @@ description: ``environ`` attribute is not implemented
cause: Unknown
workaround: Use ``getenv``, ``putenv`` and ``unsetenv``
"""
import os
try:

View file

@ -4,6 +4,7 @@ description: ``getenv`` returns actual value instead of cached value
cause: The ``environ`` attribute is not implemented
workaround: Unknown
"""
import os
print(os.getenv("NEW_VARIABLE"))

View file

@ -4,6 +4,7 @@ description: Struct pack with too few args, not checked by uPy
cause: Unknown
workaround: Unknown
"""
import struct
try:

View file

@ -4,6 +4,7 @@ description: Struct pack with too many args, not checked by uPy
cause: Unknown
workaround: Unknown
"""
import struct
try:

View file

@ -4,6 +4,7 @@ description: Struct pack with whitespace in format, whitespace ignored by CPytho
cause: MicroPython is optimised for code size.
workaround: Don't use spaces in format strings.
"""
import struct
try:

View file

@ -4,6 +4,7 @@ description: Overriding sys.stdin, sys.stdout and sys.stderr not possible
cause: They are stored in read-only memory.
workaround: Unknown
"""
import sys
sys.stdin = None

View file

@ -4,4 +4,5 @@ description: MicroPython allows using := to assign to the variable of a comprehe
cause: MicroPython is optimised for code size and doesn't check this case.
workaround: Do not rely on this behaviour if writing CPython compatible code.
"""
print([i := -1 for i in range(4)])

View file

@ -4,6 +4,7 @@ description: uPy requires spaces between literal numbers and keywords, CPy doesn
cause: Unknown
workaround: Unknown
"""
try:
print(eval("1and 0"))
except SyntaxError:

View file

@ -4,4 +4,5 @@ description: Unicode name escapes are not implemented
cause: Unknown
workaround: Unknown
"""
print("\N{LATIN SMALL LETTER A}")

View file

@ -4,6 +4,7 @@ description: Array slice assignment with unsupported RHS
cause: Unknown
workaround: Unknown
"""
b = bytearray(4)
b[0:1] = [1, 2]
print(b)

View file

@ -4,4 +4,5 @@ description: bytes objects support .format() method
cause: MicroPython strives to be a more regular implementation, so if both `str` and `bytes` support ``__mod__()`` (the % operator), it makes sense to support ``format()`` for both too. Support for ``__mod__`` can also be compiled out, which leaves only ``format()`` for bytes formatting.
workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects.
"""
print(b"{}".format(1))

View file

@ -4,4 +4,5 @@ description: bytes() with keywords not implemented
cause: Unknown
workaround: Pass the encoding as a positional parameter, e.g. ``print(bytes('abc', 'utf-8'))``
"""
print(bytes("abc", encoding="utf8"))

View file

@ -4,4 +4,5 @@ description: Bytes subscription with step != 1 not implemented
cause: MicroPython is highly optimized for memory usage.
workaround: Use explicit loop for this very rare operation.
"""
print(b"123"[0:3:2])

View file

@ -4,4 +4,5 @@ description: Dictionary keys view does not behave as a set.
cause: Not implemented.
workaround: Explicitly convert keys to a set before using set operations.
"""
print({1: 2, 3: 4}.keys() & {1})

View file

@ -4,6 +4,7 @@ description: All exceptions have readable ``value`` and ``errno`` attributes, no
cause: MicroPython is optimised to reduce code size.
workaround: Only use ``value`` on ``StopIteration`` exceptions, and ``errno`` on ``OSError`` exceptions. Do not use or rely on these attributes on other exceptions.
"""
e = Exception(1)
print(e.value)
print(e.errno)

View file

@ -4,6 +4,7 @@ description: Exception chaining not implemented
cause: Unknown
workaround: Unknown
"""
try:
raise TypeError
except TypeError:

View file

@ -4,6 +4,7 @@ description: User-defined attributes for builtin exceptions are not supported
cause: MicroPython is highly optimized for memory usage.
workaround: Use user-defined exception subclasses.
"""
e = Exception()
e.x = 0
print(e.x)

View file

@ -4,6 +4,7 @@ description: Exception in while loop condition may have unexpected line number
cause: Condition checks are optimized to happen at the end of loop body, and that line number is reported.
workaround: Unknown
"""
l = ["-foo", "-bar"]
i = 0

View file

@ -4,4 +4,5 @@ description: uPy and CPython outputs formats may differ
cause: Unknown
workaround: Unknown
"""
print("%.1g" % -9.9)

View file

@ -4,6 +4,7 @@ description: List delete with step != 1 not implemented
cause: Unknown
workaround: Use explicit loop for this rare operation.
"""
l = [1, 2, 3, 4]
del l[0:4:2]
print(l)

View file

@ -4,6 +4,7 @@ description: List slice-store with non-iterable on RHS is not implemented
cause: RHS is restricted to be a tuple or list
workaround: Use ``list(<iter>)`` on RHS to convert the iterable to a list
"""
l = [10, 20]
l[0:1] = range(4)
print(l)

View file

@ -4,6 +4,7 @@ description: List store with step != 1 not implemented
cause: Unknown
workaround: Use explicit loop for this rare operation.
"""
l = [1, 2, 3, 4]
l[0:4:2] = [5, 6]
print(l)

View file

@ -6,6 +6,7 @@ cause: CPython prevents a ``bytearray`` or ``io.bytesIO`` object from changing s
In the worst case scenario, resizing an object which is the target of a memoryview can cause the memoryview(s) to reference invalid freed memory (a use-after-free bug) and corrupt the MicroPython runtime.
workaround: Do not change the size of any ``bytearray`` or ``io.bytesIO`` object that has a ``memoryview`` assigned to it.
"""
b = bytearray(b"abcdefg")
m = memoryview(b)
b.extend(b"hijklmnop")

View file

@ -4,4 +4,5 @@ description: Start/end indices such as str.endswith(s, start) not implemented
cause: Unknown
workaround: Unknown
"""
print("abc".endswith("c", 1))

View file

@ -4,4 +4,5 @@ description: Attributes/subscr not implemented
cause: Unknown
workaround: Unknown
"""
print("{a[0]}".format(a=[1, 2]))

View file

@ -4,4 +4,5 @@ description: str(...) with keywords not implemented
cause: Unknown
workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))``
"""
print(str(b"abc", encoding="utf8"))

View file

@ -4,4 +4,5 @@ description: str.ljust() and str.rjust() not implemented
cause: MicroPython is highly optimized for memory usage. Easy workarounds available.
workaround: Instead of ``s.ljust(10)`` use ``"%-10s" % s``, instead of ``s.rjust(10)`` use ``"% 10s" % s``. Alternatively, ``"{:<10}".format(s)`` or ``"{:>10}".format(s)``.
"""
print("abc".ljust(10))

View file

@ -4,4 +4,5 @@ description: None as first argument for rsplit such as str.rsplit(None, n) not i
cause: Unknown
workaround: Unknown
"""
print("a a a".rsplit(None, 1))

View file

@ -4,4 +4,5 @@ description: Subscript with step != 1 is not yet implemented
cause: Unknown
workaround: Unknown
"""
print("abcdefghi"[0:9:2])

View file

@ -4,4 +4,5 @@ description: Tuple load with step != 1 not implemented
cause: Unknown
workaround: Unknown
"""
print((1, 2, 3, 4)[0:4:2])

View file

@ -3,6 +3,7 @@ This test need a set of pins which can be set as inputs and have no external
pull up or pull down connected.
GP12 and GP17 must be connected together
"""
from machine import Pin
import os

View file

@ -5,7 +5,7 @@ for i in range(len(s)):
# Test all three forms of Unicode escape, and
# all blocks of UTF-8 byte patterns
s = "a\xA9\xFF\u0123\u0800\uFFEE\U0001F44C"
s = "a\xa9\xff\u0123\u0800\uffee\U0001f44c"
for i in range(-len(s), len(s)):
print("s[%d]: %s %X" % (i, s[i], ord(s[i])))
print("s[:%d]: %d chars, '%s'" % (i, len(s[:i]), s[:i]))

View file

@ -22,9 +22,9 @@
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
""" gen-cpydiff generates documentation which outlines operations that differ between MicroPython
and CPython. This script is called by the docs Makefile for html and Latex and may be run
manually using the command make gen-cpydiff. """
"""gen-cpydiff generates documentation which outlines operations that differ between MicroPython
and CPython. This script is called by the docs Makefile for html and Latex and may be run
manually using the command make gen-cpydiff."""
import os
import subprocess

View file

@ -73,7 +73,7 @@ class Transport:
def repr_consumer(b):
buf.extend(b.replace(b"\x04", b""))
cmd = "import os\nfor f in os.ilistdir(%s):\n" " print(repr(f), end=',')" % (
cmd = "import os\nfor f in os.ilistdir(%s):\n print(repr(f), end=',')" % (
("'%s'" % src) if src else ""
)
try:

View file

@ -530,7 +530,7 @@ class Pyboard:
def repr_consumer(b):
buf.extend(b.replace(b"\x04", b""))
cmd = "import os\nfor f in os.ilistdir(%s):\n" " print(repr(f), end=',')" % (
cmd = "import os\nfor f in os.ilistdir(%s):\n print(repr(f), end=',')" % (
("'%s'" % src) if src else ""
)
try:

View file

@ -344,8 +344,7 @@ def read_dfu_file(filename):
# B uint8_t targets Number of targets
dfu_prefix, data = consume("<5sBIB", data, "signature version size targets")
print(
" %(signature)s v%(version)d, image size: %(size)d, "
"targets: %(targets)d" % dfu_prefix
" %(signature)s v%(version)d, image size: %(size)d, targets: %(targets)d" % dfu_prefix
)
for target_idx in range(dfu_prefix["targets"]):
# Decode the Image Prefix
@ -359,7 +358,7 @@ def read_dfu_file(filename):
# I uint32_t size Size of image (without prefix)
# I uint32_t elements Number of elements in the image
img_prefix, data = consume(
"<6sBI255s2I", data, "signature altsetting named name " "size elements"
"<6sBI255s2I", data, "signature altsetting named name size elements"
)
img_prefix["num"] = target_idx
if img_prefix["named"]: