bindings: python: build_tests: do not fallback to distutils
PATCH 1/9 bindings: python: build_tests: do not fallback to distutils
Make the assumption that the build host has setuptools>=60.2.0 which exposes the logging module and remove references to distutils.
This conforms to setuptools' logging recommendation [0].
[0]: https://setuptools.pypa.io/en/latest/deprecated/distutils-legacy.html#prefer-setuptools
--- bindings/python/build_tests.py | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-)
bindings/python/build_tests.py +3 -14
@@ -19,9 +19,11 @@ import glob import tempfile from os import getenv, path -from setuptools import Distribution, Extension +from setuptools import Distribution, Extension, logging from setuptools.command.build_ext import build_ext +logging.configure() + TOP_SRCDIR = getenv("TOP_SRCDIR", "../../") TOP_BUILDDIR = getenv("TOP_BUILDDIR", "../../")
@@ -77,19 +79,6 @@ dist = Distribution( } ) -try: - from setuptools.logging import configure - - configure() -except ImportError: - try: - from distutils.log import DEBUG, set_verbosity - - set_verbosity(DEBUG) - except ImportError: - # We can still build the tests, it will just be very quiet. - pass - with tempfile.TemporaryDirectory(prefix="libgpiod-") as temp_dir: command = build_ext(dist) command.inplace = True
Signature · 1 line
2.43.0
PATCH 2/9 bindings: python: build_tests: simplify the Distribution
The version, package, and platform information is not necessary to compile and stage the extensions, so drop that information.
If we need to add it back, we can use dist.parse_config_files() to parse information from the pyproject.toml.
--- bindings/python/build_tests.py | 6 ------ 1 file changed, 6 deletions(-)
bindings/python/build_tests.py +0 -6
@@ -27,9 +27,6 @@ logging.configure() TOP_SRCDIR = getenv("TOP_SRCDIR", "../../") TOP_BUILDDIR = getenv("TOP_BUILDDIR", "../../") -# __version__ -with open("gpiod/version.py", "r") as fd: - exec(fd.read()) # The tests are run in-place with PYTHONPATH set to bindings/python # so we need the gpiod extension module too.
@@ -72,10 +69,7 @@ system_ext = Extension( dist = Distribution( { - "name": "gpiod", "ext_modules": [gpiosim_ext, system_ext, gpiod_ext], - "version": __version__, - "platforms": ["linux"], } )
Signature · 1 line
2.43.0
PATCH 3/9 bindings: python: setup: add type annotations
In reply to Vincent FazioAdd type annotations to help with lint checks.
--- bindings/python/setup.py | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-)
bindings/python/setup.py +15 -10
@@ -1,8 +1,10 @@ # SPDX-License-Identifier: GPL-2.0-or-later # SPDX-FileCopyrightText: 2022 Bartosz Golaszewski <[email protected]> +from collections.abc import Callable from os import getenv, path, unlink from shutil import copy, copytree, rmtree +from typing import TypeVar from setuptools import Extension, setup from setuptools.command.build_ext import build_ext as orig_build_ext
@@ -10,6 +12,8 @@ from setuptools.command.sdist import log from setuptools.command.sdist import sdist as orig_sdist from setuptools.errors import BaseError +T = TypeVar("T", "sdist", "build_ext") + LINK_SYSTEM_LIBGPIOD = getenv("LINK_SYSTEM_LIBGPIOD") == "1" LIBGPIOD_MINIMUM_VERSION = "2.1" LIBGPIOD_VERSION = getenv("LIBGPIOD_VERSION")
@@ -20,7 +24,7 @@ SHA256_CHUNK_SIZE = 2048 LICENSE_FILE = "LICENSE" -def sha256(filename): +def sha256(filename: str) -> str: """ Return a sha256sum for a specific filename, loading the file in chunks to avoid potentially excessive memory use.
@@ -35,7 +39,7 @@ def sha256(filename): return sha256sum.hexdigest() -def find_sha256sum(asc_file, tar_filename): +def find_sha256sum(asc_file: str, tar_filename: str) -> str: """ Search through a local copy of sha256sums.asc for a specific filename and return the associated sha256 sum.
@@ -49,7 +53,7 @@ def find_sha256sum(asc_file, tar_filename): raise BaseError(f"no signature found for {tar_filename}") -def fetch_tarball(command): +def fetch_tarball(func: Callable[[T], None]) -> Callable[[T], None]: """ Verify the requested LIBGPIOD_VERSION tarball exists in sha256sums.asc, fetch it from https://mirrors.edge.kernel.org/pub/software/libs/libgpiod/
@@ -61,10 +65,10 @@ def fetch_tarball(command): # If no LIBGPIOD_VERSION is specified in env, just run the command if LIBGPIOD_VERSION is None: - return command + return func # If LIBGPIOD_VERSION is specified, apply the tarball wrapper - def wrapper(self): + def wrapper(cmd: T) -> None: # Just-in-time import of tarfile and urllib.request so these are # not required for Yocto to build a vendored or linked package import sys
@@ -83,7 +87,7 @@ def fetch_tarball(command): try: if open("libgpiod-version.txt", "r").read() == LIBGPIOD_VERSION: log.info(f"skipping tarball fetch") - command(self) + func(cmd) return except OSError: pass
@@ -175,13 +179,13 @@ def fetch_tarball(command): # For further details, see `egg_info.find_sources` and # `manifest_maker.add_license_files` copy(_path, LICENSE_FILE) - self.distribution.metadata.license_files = [LICENSE_FILE] + cmd.distribution.metadata.license_files = [LICENSE_FILE] # type: ignore[attr-defined] # Save the libgpiod version for sdist open("libgpiod-version.txt", "w").write(LIBGPIOD_VERSION) # Run the command - command(self) + func(cmd) # Clean up the build directory if path.exists(LICENSE_FILE):
@@ -206,8 +210,9 @@ class build_ext(orig_build_ext): """ @fetch_tarball - def run(self): + def run(self) -> None: # Try to get the gpiod version from the .txt file included in sdist + libgpiod_version: str | None try: libgpiod_version = open("libgpiod-version.txt", "r").read() except OSError:
@@ -251,7 +256,7 @@ class sdist(orig_sdist): """ @fetch_tarball - def run(self): + def run(self) -> None: super().run()
Signature · 1 line
2.43.0
PATCH 4/9 bindings: python: setup: apply linter recommendations
In reply to Vincent Fazio* Drop unneeded mode parameters
* Cast toml parsing result to dict[str, str] for expected license value
* Disambiguate the line variable type for parsing the .asc file
--- bindings/python/setup.py | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-)
bindings/python/setup.py +10 -9
@@ -4,7 +4,7 @@ from collections.abc import Callable from os import getenv, path, unlink from shutil import copy, copytree, rmtree -from typing import TypeVar +from typing import TypeVar, cast from setuptools import Extension, setup from setuptools.command.build_ext import build_ext as orig_build_ext
@@ -44,11 +44,11 @@ def find_sha256sum(asc_file: str, tar_filename: str) -> str: Search through a local copy of sha256sums.asc for a specific filename and return the associated sha256 sum. """ - with open(asc_file, "r") as f: + with open(asc_file) as f: for line in f: - line = line.strip().split(" ") - if len(line) == 2 and line[1] == tar_filename: - return line[0] + _line = line.strip().split(" ") + if len(_line) == 2 and _line[1] == tar_filename: + return _line[0] raise BaseError(f"no signature found for {tar_filename}")
@@ -85,8 +85,8 @@ def fetch_tarball(func: Callable[[T], None]) -> Callable[[T], None]: # If the version in "libgpiod-version.txt" already matches our # requested tarball, then skip the fetch altogether. try: - if open("libgpiod-version.txt", "r").read() == LIBGPIOD_VERSION: - log.info(f"skipping tarball fetch") + if open("libgpiod-version.txt").read() == LIBGPIOD_VERSION: + log.info("skipping tarball fetch") func(cmd) return except OSError:
@@ -161,7 +161,8 @@ def fetch_tarball(func: Callable[[T], None]) -> Callable[[T], None]: if sys.version_info >= (3, 11): import tomllib - license_file = tomllib.load(f).get("project").get("license") + project = cast("dict[str,str]", tomllib.load(f).get("project")) + license_file = project.get("license") else: # tomllib isn't standard, fall back to parsing by line for line in f.readlines(): _line = line.decode()
@@ -214,7 +215,7 @@ class build_ext(orig_build_ext): # Try to get the gpiod version from the .txt file included in sdist libgpiod_version: str | None try: - libgpiod_version = open("libgpiod-version.txt", "r").read() + libgpiod_version = open("libgpiod-version.txt").read() except OSError: libgpiod_version = LIBGPIOD_VERSION
Signature · 1 line
2.43.0
PATCH 5/9 bindings: python: setup: use logging module
In reply to Vincent FazioUse the logging module to conform to setuptools' recommendations [0].
[0]: https://setuptools.pypa.io/en/latest/deprecated/distutils-legacy.html#prefer-setuptools
--- bindings/python/setup.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
bindings/python/setup.py +3 -1
@@ -2,18 +2,20 @@ # SPDX-FileCopyrightText: 2022 Bartosz Golaszewski <[email protected]> from collections.abc import Callable +from logging import getLogger from os import getenv, path, unlink from shutil import copy, copytree, rmtree from typing import TypeVar, cast from setuptools import Extension, setup from setuptools.command.build_ext import build_ext as orig_build_ext -from setuptools.command.sdist import log from setuptools.command.sdist import sdist as orig_sdist from setuptools.errors import BaseError T = TypeVar("T", "sdist", "build_ext") +log = getLogger(__name__) + LINK_SYSTEM_LIBGPIOD = getenv("LINK_SYSTEM_LIBGPIOD") == "1" LIBGPIOD_MINIMUM_VERSION = "2.1" LIBGPIOD_VERSION = getenv("LIBGPIOD_VERSION")
Signature · 1 line
2.43.0
PATCH 6/9 bindings: python: examples: add type annotations
In reply to Vincent FazioAdd type annotations to help with lint checks.
--- bindings/python/examples/async_watch_line_value.py | 8 +++++--- bindings/python/examples/find_line_by_name.py | 5 +++-- bindings/python/examples/get_chip_info.py | 2 +- bindings/python/examples/get_line_info.py | 2 +- bindings/python/examples/get_line_value.py | 2 +- bindings/python/examples/get_multiple_line_values.py | 4 +++- bindings/python/examples/reconfigure_input_to_output.py | 2 +- bindings/python/examples/toggle_line_value.py | 4 ++-- bindings/python/examples/toggle_multiple_line_values.py | 6 ++++-- bindings/python/examples/watch_line_info.py | 4 +++- bindings/python/examples/watch_line_rising.py | 2 +- bindings/python/examples/watch_line_value.py | 5 +++-- bindings/python/examples/watch_multiple_line_values.py | 8 +++++--- 13 files changed, 33 insertions(+), 21 deletions(-)
bindings/python/examples/async_watch_line_value.py +5 -3
@@ -8,10 +8,12 @@ import gpiod import select from datetime import timedelta + +from gpiod.edge_event import EdgeEvent from gpiod.line import Bias, Edge -def edge_type_str(event): +def edge_type_str(event: EdgeEvent) -> str: if event.event_type is event.Type.RISING_EDGE: return "Rising" if event.event_type is event.Type.FALLING_EDGE:
@@ -19,7 +21,7 @@ def edge_type_str(event): return "Unknown" -def async_watch_line_value(chip_path, line_offset, done_fd): +def async_watch_line_value(chip_path: str, line_offset: int, done_fd: int) -> None: # Assume a button connecting the pin to ground, # so pull it up and provide some debounce. with gpiod.request_lines(
@@ -59,7 +61,7 @@ if __name__ == "__main__": # run the async executor (select.poll) in a thread to demonstrate a graceful exit. done_fd = os.eventfd(0) - def bg_thread(): + def bg_thread() -> None: try: async_watch_line_value("/dev/gpiochip0", 5, done_fd) except OSError as ex:
bindings/python/examples/find_line_by_name.py +3 -2
@@ -6,15 +6,16 @@ import gpiod import os +from collections.abc import Generator -def generate_gpio_chips(): +def generate_gpio_chips() -> Generator[str]: for entry in os.scandir("/dev/"): if gpiod.is_gpiochip_device(entry.path): yield entry.path -def find_line_by_name(line_name): +def find_line_by_name(line_name: str) -> None: # Names are not guaranteed unique, so this finds the first line with # the given name. for path in generate_gpio_chips():
bindings/python/examples/get_chip_info.py +1 -1
@@ -7,7 +7,7 @@ import gpiod -def get_chip_info(chip_path): +def get_chip_info(chip_path: str) -> None: with gpiod.Chip(chip_path) as chip: info = chip.get_info() print("{} [{}] ({} lines)".format(info.name, info.label, info.num_lines))
bindings/python/examples/get_line_info.py +1 -1
@@ -7,7 +7,7 @@ import gpiod -def get_line_info(chip_path, line_offset): +def get_line_info(chip_path: str, line_offset: int) -> None: with gpiod.Chip(chip_path) as chip: info = chip.get_line_info(line_offset) is_input = info.direction == gpiod.line.Direction.INPUT
bindings/python/examples/get_line_value.py +1 -1
@@ -9,7 +9,7 @@ import gpiod from gpiod.line import Direction -def get_line_value(chip_path, line_offset): +def get_line_value(chip_path: str, line_offset: int) -> None: with gpiod.request_lines( chip_path, consumer="get-line-value",
bindings/python/examples/get_multiple_line_values.py +3 -1
@@ -4,12 +4,14 @@ """Minimal example of reading multiple lines.""" +from collections.abc import Iterable + import gpiod from gpiod.line import Direction -def get_multiple_line_values(chip_path, line_offsets): +def get_multiple_line_values(chip_path: str, line_offsets: Iterable[int]) -> None: with gpiod.request_lines( chip_path, consumer="get-multiple-line-values",
bindings/python/examples/reconfigure_input_to_output.py +1 -1
@@ -9,7 +9,7 @@ import gpiod from gpiod.line import Direction, Value -def reconfigure_input_to_output(chip_path, line_offset): +def reconfigure_input_to_output(chip_path: str, line_offset: int) -> None: # request the line initially as an input with gpiod.request_lines( chip_path,
bindings/python/examples/toggle_line_value.py +2 -2
@@ -10,13 +10,13 @@ import time from gpiod.line import Direction, Value -def toggle_value(value): +def toggle_value(value: Value) -> Value: if value == Value.INACTIVE: return Value.ACTIVE return Value.INACTIVE -def toggle_line_value(chip_path, line_offset): +def toggle_line_value(chip_path: str, line_offset: int) -> None: value_str = {Value.ACTIVE: "Active", Value.INACTIVE: "Inactive"} value = Value.ACTIVE
bindings/python/examples/toggle_multiple_line_values.py +4 -2
@@ -10,13 +10,15 @@ import time from gpiod.line import Direction, Value -def toggle_value(value): +def toggle_value(value: Value) -> Value: if value == Value.INACTIVE: return Value.ACTIVE return Value.INACTIVE -def toggle_multiple_line_values(chip_path, line_values): +def toggle_multiple_line_values( + chip_path: str, line_values: dict[int | str, Value] +) -> None: value_str = {Value.ACTIVE: "Active", Value.INACTIVE: "Inactive"} request = gpiod.request_lines(
bindings/python/examples/watch_line_info.py +3 -1
@@ -4,10 +4,12 @@ """Minimal example of watching for info changes on particular lines.""" +from collections.abc import Iterable + import gpiod -def watch_line_info(chip_path, line_offsets): +def watch_line_info(chip_path: str, line_offsets: Iterable[int]) -> None: with gpiod.Chip(chip_path) as chip: for offset in line_offsets: chip.watch_line_info(offset)
bindings/python/examples/watch_line_rising.py +1 -1
@@ -9,7 +9,7 @@ import gpiod from gpiod.line import Edge -def watch_line_rising(chip_path, line_offset): +def watch_line_rising(chip_path: str, line_offset: int) -> None: with gpiod.request_lines( chip_path, consumer="watch-line-rising",
bindings/python/examples/watch_line_value.py +3 -2
@@ -7,10 +7,11 @@ import gpiod from datetime import timedelta +from gpiod.edge_event import EdgeEvent from gpiod.line import Bias, Edge -def edge_type_str(event): +def edge_type_str(event: EdgeEvent) -> str: if event.event_type is event.Type.RISING_EDGE: return "Rising" if event.event_type is event.Type.FALLING_EDGE:
@@ -18,7 +19,7 @@ def edge_type_str(event): return "Unknown" -def watch_line_value(chip_path, line_offset): +def watch_line_value(chip_path: str, line_offset: int) -> None: # Assume a button connecting the pin to ground, # so pull it up and provide some debounce. with gpiod.request_lines(
bindings/python/examples/watch_multiple_line_values.py +5 -3
@@ -4,12 +4,14 @@ """Minimal example of watching for edges on multiple lines.""" -import gpiod +from collections.abc import Iterable +import gpiod +from gpiod.edge_event import EdgeEvent from gpiod.line import Edge -def edge_type_str(event): +def edge_type_str(event: EdgeEvent) -> str: if event.event_type is event.Type.RISING_EDGE: return "Rising" if event.event_type is event.Type.FALLING_EDGE:
@@ -17,7 +19,7 @@ def edge_type_str(event): return "Unknown" -def watch_multiple_line_values(chip_path, line_offsets): +def watch_multiple_line_values(chip_path: str, line_offsets: Iterable[int]) -> None: with gpiod.request_lines( chip_path, consumer="watch-multiple-line-values",
Signature · 1 line
2.43.0
PATCH 7/9 bindings: python: examples: apply linter recommendations
In reply to Vincent Fazio* Sort imports
* Use f-strings where possible
* Remove usage of tuple for config key values
--- bindings/python/examples/async_watch_line_value.py | 9 ++++----- bindings/python/examples/find_line_by_name.py | 7 ++++--- bindings/python/examples/get_chip_info.py | 2 +- bindings/python/examples/get_line_info.py | 12 +++++------- bindings/python/examples/get_line_value.py | 3 +-- bindings/python/examples/get_multiple_line_values.py | 7 +++---- .../python/examples/reconfigure_input_to_output.py | 5 ++--- bindings/python/examples/toggle_line_value.py | 4 ++-- .../python/examples/toggle_multiple_line_values.py | 12 ++++-------- bindings/python/examples/watch_line_rising.py | 7 +++---- bindings/python/examples/watch_line_value.py | 10 +++++----- .../python/examples/watch_multiple_line_values.py | 12 +++++------- 12 files changed, 39 insertions(+), 51 deletions(-)
bindings/python/examples/async_watch_line_value.py +4 -5
@@ -4,11 +4,10 @@ """Minimal example of asynchronously watching for edges on a single line.""" -import gpiod import select - from datetime import timedelta +import gpiod from gpiod.edge_event import EdgeEvent from gpiod.line import Bias, Edge
@@ -48,9 +47,9 @@ def async_watch_line_value(chip_path: str, line_offset: int, done_fd: int) -> No # handle any edge events for event in request.read_edge_events(): print( - "offset: {} type: {:<7} event #{}".format( - event.line_offset, edge_type_str(event), event.line_seqno - ) + f"offset: {event.line_offset}" + f" type: {edge_type_str(event):<7}" + f" event #{event.line_seqno}" )
bindings/python/examples/find_line_by_name.py +4 -3
@@ -4,10 +4,11 @@ """Minimal example of finding a line with the given name.""" -import gpiod import os from collections.abc import Generator +import gpiod + def generate_gpio_chips() -> Generator[str]: for entry in os.scandir("/dev/"):
@@ -22,13 +23,13 @@ def find_line_by_name(line_name: str) -> None: with gpiod.Chip(path) as chip: try: offset = chip.line_offset_from_id(line_name) - print("{}: {} {}".format(line_name, chip.get_info().name, offset)) + print(f"{line_name}: {chip.get_info().name} {offset}") return except OSError: # An OSError is raised if the name is not found. continue - print("line '{}' not found".format(line_name)) + print(f"line '{line_name}' not found") if __name__ == "__main__":
bindings/python/examples/get_chip_info.py +1 -1
@@ -10,7 +10,7 @@ import gpiod def get_chip_info(chip_path: str) -> None: with gpiod.Chip(chip_path) as chip: info = chip.get_info() - print("{} [{}] ({} lines)".format(info.name, info.label, info.num_lines)) + print(f"{info.name} [{info.label}] ({info.num_lines} lines)") if __name__ == "__main__":
bindings/python/examples/get_line_info.py +5 -7
@@ -12,13 +12,11 @@ def get_line_info(chip_path: str, line_offset: int) -> None: info = chip.get_line_info(line_offset) is_input = info.direction == gpiod.line.Direction.INPUT print( - "line {:>3}: {:>12} {:>12} {:>8} {:>10}".format( - info.offset, - info.name or "unnamed", - info.consumer or "unused", - "input" if is_input else "output", - "active-low" if info.active_low else "active-high", - ) + f"line {info.offset:>3}:" + f" {info.name or 'unnamed':>12}" + f" {info.consumer or 'unused':>12}" + f" {'input' if is_input else 'output':>8}" + f" {'active-low' if info.active_low else 'active-high':>10}" )
bindings/python/examples/get_line_value.py +1 -2
@@ -5,7 +5,6 @@ """Minimal example of reading a single line.""" import gpiod - from gpiod.line import Direction
@@ -16,7 +15,7 @@ def get_line_value(chip_path: str, line_offset: int) -> None: config={line_offset: gpiod.LineSettings(direction=Direction.INPUT)}, ) as request: value = request.get_value(line_offset) - print("{}={}".format(line_offset, value)) + print(f"{line_offset}={value}") if __name__ == "__main__":
bindings/python/examples/get_multiple_line_values.py +3 -4
@@ -7,7 +7,6 @@ from collections.abc import Iterable import gpiod - from gpiod.line import Direction
@@ -15,12 +14,12 @@ def get_multiple_line_values(chip_path: str, line_offsets: Iterable[int]) -> Non with gpiod.request_lines( chip_path, consumer="get-multiple-line-values", - config={tuple(line_offsets): gpiod.LineSettings(direction=Direction.INPUT)}, + config={line_offsets: gpiod.LineSettings(direction=Direction.INPUT)}, ) as request: vals = request.get_values() - for offset, val in zip(line_offsets, vals): - print("{}={} ".format(offset, val), end="") + for offset, val in zip(line_offsets, vals, strict=True): + print(f"{offset}={val} ", end="") print()
bindings/python/examples/reconfigure_input_to_output.py +2 -3
@@ -5,7 +5,6 @@ """Example of a bi-directional line requested as input and then switched to output.""" import gpiod - from gpiod.line import Direction, Value
@@ -18,7 +17,7 @@ def reconfigure_input_to_output(chip_path: str, line_offset: int) -> None: ) as request: # read the current line value value = request.get_value(line_offset) - print("{}={} (input)".format(line_offset, value)) + print(f"{line_offset}={value} (input)") # switch the line to an output and drive it low request.reconfigure_lines( config={
@@ -29,7 +28,7 @@ def reconfigure_input_to_output(chip_path: str, line_offset: int) -> None: ) # report the current driven value value = request.get_value(line_offset) - print("{}={} (output)".format(line_offset, value)) + print(f"{line_offset}={value} (output)") if __name__ == "__main__":
bindings/python/examples/toggle_line_value.py +2 -2
@@ -4,9 +4,9 @@ """Minimal example of toggling a single line.""" -import gpiod import time +import gpiod from gpiod.line import Direction, Value
@@ -30,7 +30,7 @@ def toggle_line_value(chip_path: str, line_offset: int) -> None: }, ) as request: while True: - print("{}={}".format(line_offset, value_str[value])) + print(f"{line_offset}={value_str[value]}") time.sleep(1) value = toggle_value(value) request.set_value(line_offset, value)
bindings/python/examples/toggle_multiple_line_values.py +4 -8
@@ -4,9 +4,9 @@ """Minimal example of toggling multiple lines.""" -import gpiod import time +import gpiod from gpiod.line import Direction, Value
@@ -24,18 +24,14 @@ def toggle_multiple_line_values( request = gpiod.request_lines( chip_path, consumer="toggle-multiple-line-values", - config={ - tuple(line_values.keys()): gpiod.LineSettings(direction=Direction.OUTPUT) - }, + config={line_values.keys(): gpiod.LineSettings(direction=Direction.OUTPUT)}, output_values=line_values, ) while True: - print( - " ".join("{}={}".format(l, value_str[v]) for (l, v) in line_values.items()) - ) + print(" ".join(f"{l}={value_str[v]}" for (l, v) in line_values.items())) # noqa: E741 time.sleep(1) - for l, v in line_values.items(): + for l, v in line_values.items(): # noqa: E741 line_values[l] = toggle_value(v) request.set_values(line_values)
bindings/python/examples/watch_line_rising.py +3 -4
@@ -5,7 +5,6 @@ """Minimal example of watching for rising edges on a single line.""" import gpiod - from gpiod.line import Edge
@@ -19,9 +18,9 @@ def watch_line_rising(chip_path: str, line_offset: int) -> None: # Blocks until at least one event is available for event in request.read_edge_events(): print( - "line: {} type: Rising event #{}".format( - event.line_offset, event.line_seqno - ) + f"line: {event.line_offset}" + " type: Rising" + f" event #{event.line_seqno}" )
bindings/python/examples/watch_line_value.py +5 -5
@@ -4,9 +4,9 @@ """Minimal example of watching for edges on a single line.""" -import gpiod - from datetime import timedelta + +import gpiod from gpiod.edge_event import EdgeEvent from gpiod.line import Bias, Edge
@@ -37,9 +37,9 @@ def watch_line_value(chip_path: str, line_offset: int) -> None: # Blocks until at least one event is available for event in request.read_edge_events(): print( - "line: {} type: {:<7} event #{}".format( - event.line_offset, edge_type_str(event), event.line_seqno - ) + f"line: {event.line_offset}" + f" type: {edge_type_str(event):<7}" + f" event #{event.line_seqno}" )
bindings/python/examples/watch_multiple_line_values.py +5 -7
@@ -23,17 +23,15 @@ def watch_multiple_line_values(chip_path: str, line_offsets: Iterable[int]) -> N with gpiod.request_lines( chip_path, consumer="watch-multiple-line-values", - config={tuple(line_offsets): gpiod.LineSettings(edge_detection=Edge.BOTH)}, + config={line_offsets: gpiod.LineSettings(edge_detection=Edge.BOTH)}, ) as request: while True: for event in request.read_edge_events(): print( - "offset: {} type: {:<7} event #{} line event #{}".format( - event.line_offset, - edge_type_str(event), - event.global_seqno, - event.line_seqno, - ) + f"offset: {event.line_offset}" + f" type: {edge_type_str(event):<7}" + f" event #{event.global_seqno}" + f" line event #{event.line_seqno}" )
Signature · 1 line
2.43.0
PATCH 8/9 bindings: python: add a lint dependency group
In reply to Vincent FazioSpecify useful dependencies for linting the bindings and related code.
The group can be installed with pip install --group lint.
As part of this group, specify version ranges for mypy and ruff to keep linting consistent until new minimal versions of Python are targeted or until the new annual style introduced by ruff is chosen.
--- bindings/python/README.md | 4 +++- bindings/python/pyproject.toml | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-)
bindings/python/README.md +3 -1
@@ -120,10 +120,12 @@ When making changes, ensure type checks and linting still pass: ``` python3 -m venv venv . venv/bin/activate -pip install mypy ruff +pip install --group lint mypy; ruff format; ruff check ``` +Note that pip >=25.1 is necessary for `--group` support. + Ideally the gpiod library will continue to pass strict checks: ```
bindings/python/pyproject.toml +3 -0
@@ -33,6 +33,9 @@ classifiers = [ Homepage = "https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git" Issues = "https://github.com/brgl/libgpiod/issues/" +[dependency-groups] +lint = ["mypy>=1.18.1", "ruff~=0.15.0", "types-setuptools", "packaging"] + [tool.setuptools] platforms = ["linux"] include-package-data = false
Signature · 1 line
2.43.0
PATCH 9/9 bindings: python: update linter configuration
In reply to Vincent FazioSimplify linter configuration to check all files in the bindings directory while excluding files in .gitignore.
With a minimum mypy version of 1.18.1, the strict_equality knob can be removed as it was a work around a known issue [0] that is now fixed.
With a minimum ruff version of 15.x, rename the TCH check to TC since it was renamed in v0.8.0 [1].
[0]: https://github.com/python/mypy/issues/10910
[1]: https://github.com/astral-sh/ruff/releases/tag/0.8.0
--- bindings/python/pyproject.toml | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-)
bindings/python/pyproject.toml +3 -16
@@ -49,26 +49,13 @@ namespaces = false [tool.mypy] python_version = "3.10" +exclude_gitignore = true files = [ - "gpiod/", - "tests/", -] - -[[tool.mypy.overrides]] -module = "gpiod.line.*" -strict_equality = false # Ignore Enum comparison-overlap: https://github.com/python/mypy/issues/17317 - -[tool.ruff] -target-version = "py310" -include = [ - "gpiod/**/*.py", - "gpiod/**/*.pyi", - "tests/**/*.py", - "tests/**/*.pyi", + ".", ] [tool.ruff.lint] -select = ["B", "E", "F", "I", "TCH", "UP"] +select = ["B", "E", "F", "I", "TC", "UP"] ignore=[ # Ignore chained exception warnings for now: https://docs.astral.sh/ruff/rules/raise-without-from-inside-except/ "B904",
Signature · 1 line
2.43.0
Bartosz Golaszewski
maintainerRe: [libgpiod][PATCH 9/9] bindings: python: update linter configuration
Quoted 6 lines · Vincent Fazio
Simplify linter configuration to check all files in the bindings directory while excluding files in .gitignore.
With a minimum mypy version of 1.18.1, the
strict_equalityknob can be removed as it was a work around a known issue [0] that is now fixed.
Quoted 7 lines
With a minimum ruff version of 15.x, rename the TCH check to TC since it was renamed in v0.8.0 [1].
[0]: https://github.com/python/mypy/issues/10910
[1]: https://github.com/astral-sh/ruff/releases/tag/0.8.0Signed-off-by Vincent Fazio <[email protected]>---
Ruff checks work fine but I'm seeing this with mypy:
$ mypy build_tests.py:22: error: Library stubs not installed for "setuptools" [import-untyped] build_tests.py:23: error: Library stubs not installed for "setuptools.command.build_ext" [import-untyped] build_tests.py:23: note: Hint: "python3 -m pip install types-setuptools" build_tests.py:23: note: (or run "mypy --install-types" to install all missing stub packages) build_tests.py:23: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports setup.py:10: error: Library stubs not installed for "setuptools" [import-untyped] setup.py:11: error: Library stubs not installed for "setuptools.command.build_ext" [import-untyped] setup.py:12: error: Library stubs not installed for "setuptools.command.sdist" [import-untyped] setup.py:13: error: Library stubs not installed for "setuptools.errors" [import-untyped] Found 6 errors in 2 files (checked 45 source files)
I'm using mypy v1.20.0. Is this something with my environment?
Bart
Re: [libgpiod][PATCH 9/9] bindings: python: update linter configuration
Quoted 22 lines · Bartosz Golaszewski
Ruff checks work fine but I'm seeing this with mypy:
$ mypy build_tests.py:22: error: Library stubs not installed for "setuptools" [import-untyped] build_tests.py:23: error: Library stubs not installed for "setuptools.command.build_ext" [import-untyped] build_tests.py:23: note: Hint: "python3 -m pip install types-setuptools" build_tests.py:23: note: (or run "mypy --install-types" to install all missing stub packages) build_tests.py:23: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports setup.py:10: error: Library stubs not installed for "setuptools" [import-untyped] setup.py:11: error: Library stubs not installed for "setuptools.command.build_ext" [import-untyped] setup.py:12: error: Library stubs not installed for "setuptools.command.sdist" [import-untyped] setup.py:13: error: Library stubs not installed for "setuptools.errors" [import-untyped] Found 6 errors in 2 files (checked 45 source files)
Quoted 1 line
I'm using mypy v1.20.0. Is this something with my environment?
Yes, slightly. I guess maybe I didn't state it explicitly, but when I added patch 8, I included a list of required dependencies for type checking and called out the group in documentaiton:
https://lore.kernel.org/linux-gpio/[email protected]/T/#u
If you're running mypy from within a virtual environment, you'll need to make sure that the dependencies in that group are installed for a clean check and can use the dependency group to help with that.
If you're running mypy from the system level and outside of a virtual environment, you will have to install the distribution packages that provide the typing information.
My typical workflow for ensuring that linter checks pass:
* cd bindings/python
* python3 -m venv venv
* .venv/bin/activate
* pip install -U pip
* (now) pip install --group lint
* mypy --strict; ruff format; ruff check
Some repositories try to implement these checks as part of pre-commit hooks but I wasn't sure if we wanted to go so far as requiring these checks
Bartosz Golaszewski
maintainerRe: [libgpiod][PATCH 9/9] bindings: python: update linter configuration
Quoted 9 lines · Vincent Fazio
My typical workflow for ensuring that linter checks pass:
* cd bindings/python
* python3 -m venv venv
* .venv/bin/activate
* pip install -U pip
* (now) pip install --group lint
* mypy --strict; ruff format; ruff check
Thanks, that works.
Quoted 3 lines
Some repositories try to implement these checks as part of pre-commit hooks but I wasn't sure if we wanted to go so far as requiring these checks
How about making it part of the dist package generation?
Bart
Re: [libgpiod][PATCH 9/9] bindings: python: update linter configuration
Quoted 5 lines · Bartosz Golaszewski
Quoted 3 lines
Some repositories try to implement these checks as part of pre-commit hooks but I wasn't sure if we wanted to go so far as requiring these checks
How about making it part of the dist package generation?
If you think it would be valuable, that seems reasonable? I don't know what that entails however.
It may be "late" in the development flow, as in, at the time you want to make a dist package, the lint checks now say that there are suggested modifications or fixes necessary preventing you from building the distribution.
Ideally the lint checks are done prior to patch submission to inform users that they may have overlooked something.
It wouldn't surprise me if I'm the only one that really cares about the strict type checking and formatting. They're obviously not performing logic analysis; they just make sure that data types are correct/accounted for and all code is consistent in format.
Re: [libgpiod][PATCH 9/9] bindings: python: update linter configuration
Quoted 16 lines · Vincent Fazio
Quoted 5 lines · Bartosz Golaszewski
Quoted 3 lines
Some repositories try to implement these checks as part of pre-commit hooks but I wasn't sure if we wanted to go so far as requiring these checks
How about making it part of the dist package generation?
If you think it would be valuable, that seems reasonable? I don't know what that entails however.
It may be "late" in the development flow, as in, at the time you want to make a dist package, the lint checks now say that there are suggested modifications or fixes necessary preventing you from building the distribution.
Quoted 7 lines
Ideally the lint checks are done prior to patch submission to inform users that they may have overlooked something.
It wouldn't surprise me if I'm the only one that really cares about the strict type checking and formatting. They're obviously not performing logic analysis; they just make sure that data types are correct/accounted for and all code is consistent in format.
I do run them but don't necessarily want them as a commit hook since not everyone is working on python side of libgpiod.
I queued the patches, thanks! I have to say: it's crazy how much faster ruff is compared to mypy.
Bartosz
Re: [libgpiod][PATCH 9/9] bindings: python: update linter configuration
Quoted 3 lines · Bartosz Golaszewski
I do run them but don't necessarily want them as a commit hook since not everyone is working on python side of libgpiod.
There are tools like pre-commit [0] and prek [1] that can trigger specific actions based on what in the tree is being modified and file type if that's something you're interested in.
Quoted 3 lines
I queued the patches, thanks! I have to say: it's crazy how much faster ruff is compared to mypy.
mypy (at least the compiled version) is not too bad when it has a cache built up since it can do incremental comparisons.
There are alternatives like ty and zuban that are written in rust but mypy is the reference implementation and not all tools have the same comprehensive checks, though there is evidence [2] that I may be operating on old information.
[0]: https://github.com/pre-commit/pre-commit
[1]: https://github.com/j178/prek
[2]: https://htmlpreview.github.io/?https://github.com/python/typing/blob/main/conformance/results/results.html
Bartosz Golaszewski
AppliedQuoted 8 lines · Vincent Fazio
Make the assumption that the build host has setuptools>=60.2.0 which exposes the logging module and remove references to distutils.
This conforms to setuptools' logging recommendation [0].
[0]: https://setuptools.pypa.io/en/latest/deprecated/distutils-legacy.html#prefer-setuptools
[...]
Applied, thanks!
[1/9] bindings: python: build_tests: do not fallback to distutils
https://git.kernel.org/brgl/c/f53d6c882553198593d63e10af93ff6bbcb8a823 [2/9] bindings: python: build_tests: simplify the Distribution https://git.kernel.org/brgl/c/ddca805d92001eaaeaa86540211056f17ea0df3f [3/9] bindings: python: setup: add type annotations https://git.kernel.org/brgl/c/0bb990a59eef3191d7c1ed6a7254f935568f8b84 [4/9] bindings: python: setup: apply linter recommendations https://git.kernel.org/brgl/c/49843b8c701f7c61674912875e0dc2cb5bdb4186 [5/9] bindings: python: setup: use logging module https://git.kernel.org/brgl/c/0c466480e7791834c15458ae87cbd21fc6d608e4 [6/9] bindings: python: examples: add type annotations https://git.kernel.org/brgl/c/d130ec7666e3a5871f6b7aa261b7a305397ea28e [7/9] bindings: python: examples: apply linter recommendations https://git.kernel.org/brgl/c/485b81cd4bd5f8e9450c4587ff4a06ebae209962 [8/9] bindings: python: add a lint dependency group https://git.kernel.org/brgl/c/5efa9e8144dafa47b0ddf9366e149ddee50b6211 [9/9] bindings: python: update linter configuration https://git.kernel.org/brgl/c/530fa7823b12f91cf64bc1a9b755857049d5c2e5
Best regards,
Signature · 1 line
Bartosz Golaszewski <[email protected]>