Skip to content

Commit 362d721

Browse files
authored
Merge pull request #99 from gudnimg/types-gudni
2 parents 0770bc9 + 3ccbae3 commit 362d721

File tree

11 files changed

+29
-46
lines changed

11 files changed

+29
-46
lines changed

docs/_generate_requests_docstrings.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
import importlib.util
1313
import inspect
1414
import os
15-
from typing import Any, Optional, Type
15+
from typing import Any
1616

1717
from pydantic import BaseModel
1818

@@ -23,7 +23,7 @@ def __init__(self, name: str, lineno: int, col_offset: int, original_text: str):
2323
self.lineno = lineno
2424
self.col_offset = col_offset
2525
self.original_text = original_text
26-
self.docstring: Optional[str] = None
26+
self.docstring: str | None = None
2727

2828
def add_docstring(self, docstring: str) -> None:
2929
"""Add a docstring to the class."""
@@ -49,23 +49,23 @@ def format_docstring(docstring: str, indent: str) -> str:
4949
return '\n'.join(indented_lines)
5050

5151

52-
def get_docstring_from_parent(cls: type) -> Optional[str]:
52+
def get_docstring_from_parent(cls: type) -> str | None:
5353
"""Get the docstring from the parent class."""
5454
for base in cls.__bases__:
5555
if base.__doc__:
5656
return base.__doc__
5757
return None
5858

5959

60-
def get_field_docstring(cls: Type[BaseModel], field_name: str) -> str:
60+
def get_field_docstring(cls: type[BaseModel], field_name: str) -> str:
6161
"""Get the docstring of a field from the class."""
6262
for name, obj in inspect.getmembers(cls):
6363
if name == field_name:
6464
return obj.__doc__ or "No docstring provided."
6565
return "No docstring found."
6666

6767

68-
def format_type(annotation: Type[Any] | None) -> str:
68+
def format_type(annotation: type[Any] | None) -> str:
6969
"""Format the type to show module and class name."""
7070
if annotation is None:
7171
raise ValueError("Annotation cannot be None")
@@ -79,7 +79,7 @@ def format_type(annotation: Type[Any] | None) -> str:
7979
return str(annotation) # Fallback for other types
8080

8181

82-
def get_pydantic_fields(cls: Type[BaseModel]) -> str:
82+
def get_pydantic_fields(cls: type[BaseModel]) -> str:
8383
"""Get the fields of a Pydantic model and format them as Google-style Args."""
8484
if not issubclass(cls, BaseModel):
8585
return ""
@@ -109,7 +109,7 @@ def get_pydantic_fields(cls: Type[BaseModel]) -> str:
109109

110110
def parse_file(file_path: str) -> list[ClassInfo]:
111111
"""Parse the file and extract class definitions."""
112-
with open(file_path, 'r') as file:
112+
with open(file_path) as file:
113113
lines = file.readlines()
114114
tree = ast.parse(''.join(lines))
115115

@@ -146,7 +146,7 @@ def update_class_docstrings(file_path: str) -> None:
146146
full_docstring = parent_docstring + args_section
147147
class_info.add_docstring(full_docstring)
148148

149-
with open(file_path, 'r', encoding="utf-8") as file:
149+
with open(file_path, encoding="utf-8") as file:
150150
lines = file.readlines()
151151

152152
updated_lines = []

examples/usb/download_file.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ async def main() -> None:
2121
file_data = await client.download_file(file_location)
2222
end_s = time.time()
2323
duration = end_s - start_s
24-
speed = round(len(file_data) / ((duration)) / 1000, 2)
24+
speed = round(len(file_data) / duration / 1000, 2)
2525

2626
print(f"Speed {speed} KB/s")
2727

smpclient/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,10 @@
2626
import asyncio
2727
import logging
2828
import traceback
29+
from collections.abc import AsyncIterator
2930
from hashlib import sha256
3031
from types import TracebackType
31-
from typing import AsyncIterator, Final, Type
32+
from typing import Final
3233

3334
from pydantic import ValidationError
3435
from smp import header as smpheader
@@ -414,7 +415,7 @@ async def __aenter__(self) -> "SMPClient":
414415

415416
async def __aexit__(
416417
self,
417-
exc_type: Type[BaseException] | None,
418+
exc_type: type[BaseException] | None,
418419
exc_value: BaseException | None,
419420
tb: TracebackType | None,
420421
) -> None:

smpclient/extensions/intercreate.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""Intercreate extensions of the `SMPClient`."""
22

3-
from typing import AsyncIterator, Final
3+
from collections.abc import AsyncIterator
4+
from typing import Final
45

56
from smp import header as smpheader
67

smpclient/generics.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"""Generics and Type Narrowing for SMP Requests and Responses."""
22

3-
from typing import Protocol, Type, TypeVar, Union
3+
from typing import Protocol, TypeVar, Union
44

55
from smp import error as smperror
66
from smp import header as smphdr
@@ -32,9 +32,9 @@ class ImageStatesRead(smpimg.ImageStatesReadRequest):
3232
```
3333
"""
3434

35-
_Response: Type[TRep]
36-
_ErrorV1: Type[TEr1]
37-
_ErrorV2: Type[TEr2]
35+
_Response: type[TRep]
36+
_ErrorV1: type[TEr1]
37+
_ErrorV2: type[TEr2]
3838

3939
@property
4040
def BYTES(self) -> bytes: # pragma: no cover

smpclient/transport/ble.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
import logging
55
import re
66
import sys
7-
from typing import Final, Protocol
7+
from typing import Final, Protocol, TypeGuard
88
from uuid import UUID
99

1010
from bleak import BleakClient, BleakGATTCharacteristic, BleakScanner
1111
from bleak.args.winrt import WinRTClientArgs
1212
from bleak.backends.client import BaseBleakClient
1313
from bleak.backends.device import BLEDevice
1414
from smp import header as smphdr
15-
from typing_extensions import TypeGuard, override
15+
from typing_extensions import override
1616

1717
from smpclient.exceptions import SMPClientException
1818
from smpclient.transport import SMPTransport, SMPTransportDisconnected

smpclient/transport/serial.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ async def read_serial(self, delimiter: bytes | None = None) -> bytes:
227227
try:
228228
first_match, remaining_data = self._serial_buffer.split(delimiter, 1)
229229
except ValueError:
230-
return bytes()
230+
return b''
231231
self._serial_buffer = remaining_data
232232
return bytes(first_match)
233233

tests/fixtures/analyze-mcuboot-img.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ def main():
107107
print('Initial image bytes:')
108108
start = img_header.hdr_size
109109
end = start + min(20, img_header.img_size)
110-
print('\t' + ' '.join('{:02x}'.format(b) for b in contents[start:end]))
110+
print('\t' + ' '.join(f'{b:02x}' for b in contents[start:end]))
111111

112112
tlv_info_offset = img_header.hdr_size + img_header.img_size
113113
tlv_info = TLVInfo(*struct.unpack_from(TLV_INFO_FMT, contents, offset=tlv_info_offset))
@@ -117,11 +117,11 @@ def main():
117117
tlv_num = 0
118118
while tlv_off < tlv_end:
119119
tlv_hdr = TLVHeader(*struct.unpack_from(TLV_HDR_FMT, contents, offset=tlv_off))
120-
print('TLV {}:'.format(tlv_num), tlv_hdr)
120+
print(f'TLV {tlv_num}:', tlv_hdr)
121121
if tlv_hdr.len <= 32:
122122
start = tlv_off + TLV_HDR_SIZE
123123
end = start + tlv_hdr.len
124-
print('\t' + ' '.join('{:02x}'.format(b) for b in contents[start:end]))
124+
print('\t' + ' '.join(f'{b:02x}' for b in contents[start:end]))
125125
tlv_off += TLV_HDR_SIZE + tlv_hdr.len
126126
tlv_num += 1
127127

tests/test_requests.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
"""Test the `SMPRequest` `Protocol` implementations."""
22

3-
from typing import Type
4-
53
import pytest
64
from smp import enumeration_management as smpem
75
from smp import error as smperr
@@ -297,9 +295,9 @@ def test_requests(
297295
test_tuple: tuple[
298296
smpmsg.Request,
299297
SMPRequest[TRep, TEr1, TEr2],
300-
Type[smpmsg.Response],
301-
Type[smperr.ErrorV1],
302-
Type[smperr.ErrorV2],
298+
type[smpmsg.Response],
299+
type[smperr.ErrorV1],
300+
type[smperr.ErrorV2],
303301
],
304302
) -> None:
305303
a, b, Response, ErrorV1, ErrorV2 = test_tuple

tests/test_smp_client.py

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
"""Tests for `SMPClient`."""
22

3-
import sys
43
from hashlib import sha256
54
from pathlib import Path
65
from unittest.mock import AsyncMock, PropertyMock, call, patch
@@ -39,23 +38,6 @@
3938
from smpclient.requests.os_management import ResetWrite
4039
from smpclient.transport.serial import SMPSerialTransport
4140

42-
if sys.version_info < (3, 10):
43-
from typing import Any
44-
45-
async def anext(iterator: Any, default: Any = None) -> Any:
46-
try:
47-
return await iterator.__anext__()
48-
except StopAsyncIteration:
49-
if default is None:
50-
raise
51-
return default
52-
53-
def aiter(iterable: Any) -> Any:
54-
if hasattr(iterable, '__aiter__'):
55-
return iterable.__aiter__()
56-
else:
57-
raise TypeError(f"{iterable} is not async iterable")
58-
5941

6042
class SMPMockTransport:
6143
"""Satisfies the `SMPTransport` `Protocol`."""

0 commit comments

Comments
 (0)