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: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
# ruff version should be kept in sync with .pre-commit-config.yaml # 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 check --output-format=github .
- run: ruff format --diff . - run: ruff format --diff .

View File

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

View File

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

View File

@@ -27,6 +27,17 @@ line-length = 99
target-version = "py37" target-version = "py37"
[tool.ruff.lint] [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"] extend-select = ["C9", "PLC"]
ignore = [ ignore = [
"E401", "E401",
@@ -37,14 +48,12 @@ ignore = [
"F401", "F401",
"F403", "F403",
"F405", "F405",
"PLC1901", "PLC0206",
] ]
mccabe.max-complexity = 40
[tool.ruff.mccabe] [tool.ruff.lint.per-file-ignores]
max-complexity = 40 # Exclude all tests from linting.
[tool.ruff.per-file-ignores]
# Exclude all tests from linting (does not apply to formatting).
"tests/**/*.py" = ["ALL"] "tests/**/*.py" = ["ALL"]
"ports/cc3200/tools/uniflash.py" = ["E711"] "ports/cc3200/tools/uniflash.py" = ["E711"]
# manifest.py files are evaluated with some global names pre-defined # manifest.py files are evaluated with some global names pre-defined
@@ -57,3 +66,4 @@ max-complexity = 40
# repl_: not real python files # repl_: not real python files
# viper_args: uses f(*) # viper_args: uses f(*)
exclude = ["tests/basics/*.py", "tests/*/repl_*.py", "tests/micropython/viper_args.py"] 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: except StopIteration:
val = deflt val = deflt
""" """
print(next(iter(range(0)), 42)) print(next(iter(range(0)), 42))

View File

@@ -4,6 +4,7 @@ description: Special method __del__ not implemented for user-defined classes
cause: Unknown cause: Unknown
workaround: Unknown workaround: Unknown
""" """
import gc 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 x, y = 1, 2
# fmt: off
print("aa" f"{x}") # works print("aa" f"{x}") # works
print(f"{x}" "ab") # works print(f"{x}" "ab") # works
print("a{}a" f"{x}") # fails print("a{}a" f"{x}") # fails
print(f"{x}" "a{}b") # 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. cause: MicroPython counts "self" as an argument.
workaround: Interpret error messages with the information above in mind. workaround: Interpret error messages with the information above in mind.
""" """
try: try:
[].append() [].append()
except Exception as e: except Exception as e:

View File

@@ -4,6 +4,7 @@ description: __all__ is unsupported in __init__.py in MicroPython.
cause: Not implemented. cause: Not implemented.
workaround: Manually import the sub-modules directly in __init__.py using ``from . import foo, bar``. workaround: Manually import the sub-modules directly in __init__.py using ``from . import foo, bar``.
""" """
from modules3 import * from modules3 import *
foo.hello() 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. 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. workaround: Details of import handling is inherently implementation dependent. Don't rely on such details in portable applications.
""" """
import modules import modules
print(modules.__path__) 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. 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). 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 import sys
sys.path.append(sys.path[1] + "/modules") 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())``. 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 workaround: Unknown
""" """
val = 1 val = 1

View File

@@ -4,6 +4,7 @@ description: Comparison between different typecodes not supported
cause: Code size cause: Code size
workaround: Compare individual elements workaround: Compare individual elements
""" """
import array import array
array.array("b", [1, 2]) == array.array("i", [1, 2]) 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 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 workaround: If CPython compatibility is needed then mask the value explicitly
""" """
import array import array
a = array.array("b", [257]) a = array.array("b", [257])

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -4,6 +4,7 @@ description: Struct pack with too many args, not checked by uPy
cause: Unknown cause: Unknown
workaround: Unknown workaround: Unknown
""" """
import struct import struct
try: 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. cause: MicroPython is optimised for code size.
workaround: Don't use spaces in format strings. workaround: Don't use spaces in format strings.
""" """
import struct import struct
try: 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. cause: They are stored in read-only memory.
workaround: Unknown workaround: Unknown
""" """
import sys import sys
sys.stdin = None 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. 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. workaround: Do not rely on this behaviour if writing CPython compatible code.
""" """
print([i := -1 for i in range(4)]) 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 cause: Unknown
workaround: Unknown workaround: Unknown
""" """
try: try:
print(eval("1and 0")) print(eval("1and 0"))
except SyntaxError: except SyntaxError:

View File

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

View File

@@ -4,6 +4,7 @@ description: Array slice assignment with unsupported RHS
cause: Unknown cause: Unknown
workaround: Unknown workaround: Unknown
""" """
b = bytearray(4) b = bytearray(4)
b[0:1] = [1, 2] b[0:1] = [1, 2]
print(b) 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. 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. workaround: If you are interested in CPython compatibility, don't use ``.format()`` on bytes objects.
""" """
print(b"{}".format(1)) print(b"{}".format(1))

View File

@@ -4,4 +4,5 @@ description: bytes() with keywords not implemented
cause: Unknown cause: Unknown
workaround: Pass the encoding as a positional parameter, e.g. ``print(bytes('abc', 'utf-8'))`` workaround: Pass the encoding as a positional parameter, e.g. ``print(bytes('abc', 'utf-8'))``
""" """
print(bytes("abc", encoding="utf8")) 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. cause: MicroPython is highly optimized for memory usage.
workaround: Use explicit loop for this very rare operation. workaround: Use explicit loop for this very rare operation.
""" """
print(b"123"[0:3:2]) 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. cause: Not implemented.
workaround: Explicitly convert keys to a set before using set operations. workaround: Explicitly convert keys to a set before using set operations.
""" """
print({1: 2, 3: 4}.keys() & {1}) 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. 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. 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) e = Exception(1)
print(e.value) print(e.value)
print(e.errno) print(e.errno)

View File

@@ -4,6 +4,7 @@ description: Exception chaining not implemented
cause: Unknown cause: Unknown
workaround: Unknown workaround: Unknown
""" """
try: try:
raise TypeError raise TypeError
except 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. cause: MicroPython is highly optimized for memory usage.
workaround: Use user-defined exception subclasses. workaround: Use user-defined exception subclasses.
""" """
e = Exception() e = Exception()
e.x = 0 e.x = 0
print(e.x) 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. cause: Condition checks are optimized to happen at the end of loop body, and that line number is reported.
workaround: Unknown workaround: Unknown
""" """
l = ["-foo", "-bar"] l = ["-foo", "-bar"]
i = 0 i = 0

View File

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

View File

@@ -4,6 +4,7 @@ description: List delete with step != 1 not implemented
cause: Unknown cause: Unknown
workaround: Use explicit loop for this rare operation. workaround: Use explicit loop for this rare operation.
""" """
l = [1, 2, 3, 4] l = [1, 2, 3, 4]
del l[0:4:2] del l[0:4:2]
print(l) 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 cause: RHS is restricted to be a tuple or list
workaround: Use ``list(<iter>)`` on RHS to convert the iterable to a list workaround: Use ``list(<iter>)`` on RHS to convert the iterable to a list
""" """
l = [10, 20] l = [10, 20]
l[0:1] = range(4) l[0:1] = range(4)
print(l) print(l)

View File

@@ -4,6 +4,7 @@ description: List store with step != 1 not implemented
cause: Unknown cause: Unknown
workaround: Use explicit loop for this rare operation. workaround: Use explicit loop for this rare operation.
""" """
l = [1, 2, 3, 4] l = [1, 2, 3, 4]
l[0:4:2] = [5, 6] l[0:4:2] = [5, 6]
print(l) 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. 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. workaround: Do not change the size of any ``bytearray`` or ``io.bytesIO`` object that has a ``memoryview`` assigned to it.
""" """
b = bytearray(b"abcdefg") b = bytearray(b"abcdefg")
m = memoryview(b) m = memoryview(b)
b.extend(b"hijklmnop") b.extend(b"hijklmnop")

View File

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

View File

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

View File

@@ -4,4 +4,5 @@ description: str(...) with keywords not implemented
cause: Unknown cause: Unknown
workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))`` workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))``
""" """
print(str(b"abc", encoding="utf8")) 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. 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)``. 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)) 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 cause: Unknown
workaround: Unknown workaround: Unknown
""" """
print("a a a".rsplit(None, 1)) print("a a a".rsplit(None, 1))

View File

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

View File

@@ -4,4 +4,5 @@ description: Tuple load with step != 1 not implemented
cause: Unknown cause: Unknown
workaround: Unknown workaround: Unknown
""" """
print((1, 2, 3, 4)[0:4:2]) 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. pull up or pull down connected.
GP12 and GP17 must be connected together GP12 and GP17 must be connected together
""" """
from machine import Pin from machine import Pin
import os import os

View File

@@ -5,7 +5,7 @@ for i in range(len(s)):
# Test all three forms of Unicode escape, and # Test all three forms of Unicode escape, and
# all blocks of UTF-8 byte patterns # 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)): for i in range(-len(s), len(s)):
print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) print("s[%d]: %s %X" % (i, s[i], ord(s[i])))
print("s[:%d]: %d chars, '%s'" % (i, len(s[:i]), 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 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE. # THE SOFTWARE.
""" gen-cpydiff generates documentation which outlines operations that differ between MicroPython """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 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. """ manually using the command make gen-cpydiff."""
import os import os
import subprocess import subprocess

View File

@@ -73,7 +73,7 @@ class Transport:
def repr_consumer(b): def repr_consumer(b):
buf.extend(b.replace(b"\x04", 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 "" ("'%s'" % src) if src else ""
) )
try: try:

View File

@@ -530,7 +530,7 @@ class Pyboard:
def repr_consumer(b): def repr_consumer(b):
buf.extend(b.replace(b"\x04", 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 "" ("'%s'" % src) if src else ""
) )
try: try:

View File

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