diff --git a/micropy/app/stubs.py b/micropy/app/stubs.py index 643332b2a..ec6560904 100644 --- a/micropy/app/stubs.py +++ b/micropy/app/stubs.py @@ -179,7 +179,7 @@ def _get_desc(name: str, cfg: dict): pyb.run_script(create_stubs, DevicePath(dev_path)) except Exception as e: # TODO: Handle more usage cases - log.error(f"Failed to execute script: {str(e)}", exception=e) + log.error(f"Failed to execute script: {e!s}", exception=e) raise log.success("Done!") log.info("Copying stubs...") diff --git a/micropy/exceptions.py b/micropy/exceptions.py index 94cf35109..18fe5a308 100644 --- a/micropy/exceptions.py +++ b/micropy/exceptions.py @@ -1,6 +1,8 @@ """Micropy Exceptions.""" from __future__ import annotations +from typing import Optional + class MicropyException(Exception): """Generic MicroPy Exception.""" @@ -21,7 +23,7 @@ class StubValidationError(StubError): """Raised when a stub fails validation.""" def __init__(self, path, errors, *args, **kwargs): - msg = f"Stub at[{str(path)}] encountered" f" the following validation errors: {str(errors)}" + msg = f"Stub at[{path!s}] encountered" f" the following validation errors: {errors!s}" super().__init__(msg, *args, **kwargs) def __str__(self): @@ -52,7 +54,7 @@ class RequirementNotFound(RequirementException): class PyDeviceError(MicropyException): """Generic PyDevice exception.""" - def __init__(self, message: str = None): + def __init__(self, message: Optional[str] = None): super().__init__(message) self.message = message diff --git a/micropy/logger.py b/micropy/logger.py index 80988741e..953c202c7 100644 --- a/micropy/logger.py +++ b/micropy/logger.py @@ -254,7 +254,7 @@ def exception(self, error, **kwargs): """ name = type(error).__name__ - msg = f"{name}: {str(error)}" + msg = f"{name}: {error!s}" return self.echo(msg, log="exception", title_color="red", fg="red", accent="red", **kwargs) def success(self, msg, **kwargs): diff --git a/micropy/project/modules/stubs.py b/micropy/project/modules/stubs.py index 186ed6320..bf17336e2 100644 --- a/micropy/project/modules/stubs.py +++ b/micropy/project/modules/stubs.py @@ -2,7 +2,7 @@ import sys from pathlib import Path -from typing import Any, List, Sequence, Union +from typing import Any, List, Optional, Sequence, Union from boltons import setutils from micropy.project.modules import ProjectModule @@ -22,7 +22,7 @@ class StubsModule(ProjectModule): PRIORITY: int = 9 def __init__( - self, stub_manager: StubManager, stubs: Sequence[DeviceStub] = None, **kwargs: Any + self, stub_manager: StubManager, stubs: Optional[Sequence[DeviceStub]] = None, **kwargs: Any ): super().__init__(**kwargs) self.stub_manager: StubManager = stub_manager diff --git a/micropy/project/template.py b/micropy/project/template.py index 3ae97febc..0bf17aa66 100644 --- a/micropy/project/template.py +++ b/micropy/project/template.py @@ -296,7 +296,7 @@ def render_to(self, name, parent_dir, *args, **kwargs): """ template = self.get(name, **kwargs) - self.log.debug(f"Loaded: {str(template)}") + self.log.debug(f"Loaded: {template!s}") if self.run_checks: self.log.debug(f"Verifying {template} requirements...") template.run_checks() @@ -305,7 +305,7 @@ def render_to(self, name, parent_dir, *args, **kwargs): self.log.debug(f"Create: {out_dir}") parent_dir.mkdir(exist_ok=True) out_dir.parent.mkdir(exist_ok=True, parents=True) - self.log.debug(f"Rendered: {name} to {str(out_dir)}") + self.log.debug(f"Rendered: {name} to {out_dir!s}") self.log.info(f"$[{name.capitalize()}] File Generated!") stream = template.render_stream() return stream.dump(str(out_dir)) @@ -326,13 +326,13 @@ def update(self, name, root_dir, **kwargs): """ template = self.get(name, **kwargs) - self.log.debug(f"Loaded: {str(template)}") + self.log.debug(f"Loaded: {template!s}") try: template.update(root_dir) except FileNotFoundError: self.log.debug("Template does not exist!") return self.render_to(name, root_dir, **kwargs) - self.log.debug(f"Updated: {str(template)}") + self.log.debug(f"Updated: {template!s}") return template @property diff --git a/micropy/pyd/abc.py b/micropy/pyd/abc.py index 28793d334..1208ece18 100644 --- a/micropy/pyd/abc.py +++ b/micropy/pyd/abc.py @@ -3,14 +3,14 @@ import abc from io import BytesIO, StringIO from pathlib import Path -from typing import Any, AnyStr, Generic, NewType, Protocol, TypeVar +from typing import Any, AnyStr, Generic, NewType, Optional, Protocol, TypeVar HostPath = NewType("HostPath", str) DevicePath = NewType("DevicePath", str) class StartHandler(Protocol): - def __call__(self, *, name: str = None, size: int | None = None) -> Any: + def __call__(self, *, name: Optional[str] = None, size: int | None = None) -> Any: ... diff --git a/micropy/pyd/backend_upydevice.py b/micropy/pyd/backend_upydevice.py index 834769333..413ffca42 100644 --- a/micropy/pyd/backend_upydevice.py +++ b/micropy/pyd/backend_upydevice.py @@ -203,7 +203,7 @@ def write_file( target_path = self.resolve_path(target_path) self._pydevice.cmd("import gc") self._pydevice.cmd("import ubinascii") - self._pydevice.cmd(f"f = open('{str(target_path)}', 'wb')") + self._pydevice.cmd(f"f = open('{target_path!s}', 'wb')") content_iter = ( iterutils.chunked_iter(contents, self.BUFFER_SIZE) @@ -212,7 +212,7 @@ def write_file( ) content_size = len(contents) - consumer.on_start(name=f"Writing {str(target_path)}", size=content_size) + consumer.on_start(name=f"Writing {target_path!s}", size=content_size) for chunk in content_iter: cmd = ( diff --git a/micropy/pyd/consumers.py b/micropy/pyd/consumers.py index a6b333b7a..b6d7fda1b 100644 --- a/micropy/pyd/consumers.py +++ b/micropy/pyd/consumers.py @@ -1,7 +1,7 @@ from __future__ import annotations from functools import partialmethod -from typing import Any, Callable, NamedTuple, cast +from typing import Any, Callable, NamedTuple, Optional, cast from micropy.pyd.abc import ( EndHandler, @@ -19,14 +19,14 @@ class ProgressStreamConsumer: def __init__( self, - on_description: Callable[ - [str, dict[str, Any] | None], tuple[str, dict[str, Any] | None] + on_description: Optional[ + Callable[[str, dict[str, Any] | None], tuple[str, dict[str, Any] | None]] ] = None, **kwargs, ): self._on_description = on_description or (lambda s, cfg: (s, cfg)) - def on_start(self, *, name: str = None, size: int | None = None): + def on_start(self, *, name: Optional[str] = None, size: int | None = None): bar_format = "{l_bar}{bar}| [{n_fmt}/{total_fmt} @ {rate_fmt}]" tqdm_kwargs = { "unit_scale": True, diff --git a/tests/test_highlevel.py b/tests/test_highlevel.py index 11e559ea9..9fcf973fb 100644 --- a/tests/test_highlevel.py +++ b/tests/test_highlevel.py @@ -61,7 +61,7 @@ def build_project(self, mpy, path): if proj_path.exists(): shutil.rmtree(proj_path, ignore_errors=True) proj = project.Project(proj_path) - proj_stub = list(mpy.stubs)[0] + proj_stub = next(iter(mpy.stubs)) proj.add(project.modules.StubsModule, mpy.stubs, stubs=[proj_stub]) proj.add(project.modules.PackagesModule, "requirements.txt") proj.add(project.modules.DevPackagesModule, "dev-requirements.txt") diff --git a/tests/test_project.py b/tests/test_project.py index d68c57a61..47b3de463 100644 --- a/tests/test_project.py +++ b/tests/test_project.py @@ -203,7 +203,7 @@ def stub_module(self, mocker, tmp_path, micropy_stubs): mp = micropy_stubs() parent_mock = mocker.MagicMock() parent_mock.data_path = tmp_path / ".micropy" - stub_item = list(mp.stubs)[0] + stub_item = next(iter(mp.stubs)) stub_mod = modules.StubsModule( mp.stubs, stubs=[stub_item], parent=parent_mock, log=mocker.Mock() ) diff --git a/tests/test_stubs.py b/tests/test_stubs.py index ac748a636..e551c5594 100644 --- a/tests/test_stubs.py +++ b/tests/test_stubs.py @@ -176,7 +176,7 @@ def __init__(self, path, copy_to=None, **kwargs): def test_stub_resolve_link(mock_mp_stubs, tmp_path): """should create DeviceStub from symlink""" - stub = list(mock_mp_stubs.stubs)[0] + stub = next(iter(mock_mp_stubs.stubs)) link_path = tmp_path / "stub_symlink" linked_stub = stubs.stubs.DeviceStub.resolve_link(stub, link_path) assert stub == linked_stub @@ -191,7 +191,7 @@ def test_manager_resolve_subresource(mock_mp_stubs, tmp_path): subresource = tmp_path / "stub_subresource" subresource.mkdir() manager = mock_mp_stubs.stubs.resolve_subresource(test_stubs, subresource) - linked_stub = list(manager)[0] + linked_stub = next(iter(manager)) assert linked_stub.path.is_symlink() assert linked_stub in list(mock_mp_stubs.stubs)