1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-18 04:18:10 +00:00

style(python): upgrade to pyright 1.1.361

had to add a typestub for PIL due to
https://github.com/microsoft/pyright/issues/7832

We should remove it if that is either fixed or, if I fail to convince
Eric, after the relevant type information is added to Pillow

[no changelog]
This commit is contained in:
matejcik 2024-05-02 14:49:49 +02:00 committed by matejcik
parent 8640b50d81
commit a5aa515631
14 changed files with 1488 additions and 21 deletions

View File

@ -4,10 +4,13 @@
"tools", "tools",
"helper-scripts" "helper-scripts"
], ],
"stubPath": "./stubs",
"pythonVersion": "3.8", "pythonVersion": "3.8",
"typeCheckingMode": "basic", "typeCheckingMode": "basic",
"reportMissingImports": false, "reportMissingImports": false,
"reportUntypedFunctionDecorator": true, "reportUntypedFunctionDecorator": true,
"reportUntypedClassDecorator": true, "reportUntypedClassDecorator": true,
"reportMissingParameterType": true "reportMissingParameterType": true,
"useLibraryCodeForTypes": false,
"reportMissingModuleSource": false
} }

View File

@ -158,7 +158,7 @@ def with_client(func: "Callable[Concatenate[TrezorClient, P], R]") -> "Callable[
# the return type of @click.pass_obj is improperly specified and pyright doesn't # the return type of @click.pass_obj is improperly specified and pyright doesn't
# understand that it converts f(obj, *args, **kwargs) to f(*args, **kwargs) # understand that it converts f(obj, *args, **kwargs) to f(*args, **kwargs)
return trezorctl_command_with_client # type: ignore [cannot be assigned to return type] return trezorctl_command_with_client # type: ignore [is incompatible with return type]
class AliasedGroup(click.Group): class AliasedGroup(click.Group):

View File

@ -94,7 +94,7 @@ def _amount_to_int(
if value.isdigit(): if value.isdigit():
return int(value) return int(value)
try: try:
number, unit = re.match(r"^(\d+(?:.\d+)?)([a-z]+)", value).groups() # type: ignore ["groups" is not a known member of "None"] number, unit = re.match(r"^(\d+(?:.\d+)?)([a-z]+)", value).groups() # type: ignore ["groups" is not a known attribute of "None"]
scale = ETHER_UNITS[unit] scale = ETHER_UNITS[unit]
decoded_number = Decimal(number) decoded_number = Decimal(number)
return int(decoded_number * scale) return int(decoded_number * scale)

View File

@ -119,7 +119,7 @@ class TrezorctlGroup(AliasedGroup):
command, subcommand = cmd_name.split("-", maxsplit=1) command, subcommand = cmd_name.split("-", maxsplit=1)
# get_command can return None and the following line will fail. # get_command can return None and the following line will fail.
# We don't care, we ignore the exception anyway. # We don't care, we ignore the exception anyway.
return super().get_command(ctx, command).get_command(ctx, subcommand) # type: ignore ["get_command" is not a known member of "None";;Cannot access member "get_command" for type "Command"] return super().get_command(ctx, command).get_command(ctx, subcommand) # type: ignore [get_command]
except Exception: except Exception:
pass pass
@ -143,7 +143,7 @@ class TrezorctlGroup(AliasedGroup):
from click import __version__ as click_version from click import __version__ as click_version
if click_version.startswith("7."): if click_version.startswith("7."):
return super().resultcallback() # type: ignore [Cannot access member] return super().resultcallback() # type: ignore [Cannot access attribute]
else: else:
return super().result_callback() return super().result_callback()

View File

@ -123,7 +123,7 @@ class TrezorClient(Generic[UI]):
LOG.info(f"creating client instance for device: {transport.get_path()}") LOG.info(f"creating client instance for device: {transport.get_path()}")
# Here, self.model could be set to None. Unless _init_device is False, it will # Here, self.model could be set to None. Unless _init_device is False, it will
# get correctly reconfigured as part of the init_device flow. # get correctly reconfigured as part of the init_device flow.
self.model = model # type: ignore [Type "None" cannot be assigned] self.model = model # type: ignore ["None" is incompatible with "TrezorModel"]
if self.model: if self.model:
self.mapping = self.model.default_mapping self.mapping = self.model.default_mapping
else: else:

View File

@ -139,7 +139,7 @@ class TarSource(Source):
inner_name = "/".join(components) inner_name = "/".join(components)
LOG.info("Extracting definition from %s:%s", self.archive.name, inner_name) LOG.info("Extracting definition from %s:%s", self.archive.name, inner_name)
try: try:
return self.archive.extractfile(inner_name).read() # type: ignore [not a known member] return self.archive.extractfile(inner_name).read() # type: ignore [not a known attribute]
except Exception: except Exception:
LOG.info("Requested definition at %s was not found", inner_name) LOG.info("Requested definition at %s was not found", inner_name)
return None return None

View File

@ -14,10 +14,14 @@
# You should have received a copy of the License along with this library. # You should have received a copy of the License along with this library.
# If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>. # If not, see <https://www.gnu.org/licenses/lgpl-3.0.html>.
from __future__ import annotations
import io import io
from types import ModuleType from types import ModuleType
from typing import Dict, Optional, Tuple, Type, TypeVar from typing import Dict, Optional, Tuple, Type, TypeVar
from typing_extensions import Self
from . import messages, protobuf from . import messages, protobuf
T = TypeVar("T") T = TypeVar("T")
@ -71,7 +75,7 @@ class ProtobufMapping:
return protobuf.load_message(buf, cls) return protobuf.load_message(buf, cls)
@classmethod @classmethod
def from_module(cls: Type[T], module: ModuleType) -> T: def from_module(cls, module: ModuleType) -> Self:
"""Generate a mapping from a module. """Generate a mapping from a module.
The module must have a `MessageType` enum that specifies individual wire types. The module must have a `MessageType` enum that specifies individual wire types.

View File

@ -183,9 +183,9 @@ class Field:
class _MessageTypeMeta(type): class _MessageTypeMeta(type):
def __init__(cls, name: str, bases: tuple, d: dict) -> None: def __init__(cls, name: str, bases: tuple, d: dict) -> None:
super().__init__(name, bases, d) # type: ignore [Expected 1 positional argument] super().__init__(name, bases, d)
if name != "MessageType": if name != "MessageType":
cls.__init__ = MessageType.__init__ # type: ignore ["__init__" is obscured by a declaration of the same name;;Cannot assign member "__init__" for type "_MessageTypeMeta"] cls.__init__ = MessageType.__init__ # type: ignore [Parameter]
class MessageType(metaclass=_MessageTypeMeta): class MessageType(metaclass=_MessageTypeMeta):
@ -209,6 +209,7 @@ class MessageType(metaclass=_MessageTypeMeta):
for field, val in zip_longest(self.FIELDS.values(), args, fillvalue=MISSING): for field, val in zip_longest(self.FIELDS.values(), args, fillvalue=MISSING):
if field is MISSING: if field is MISSING:
raise TypeError("too many positional arguments") raise TypeError("too many positional arguments")
assert isinstance(field, Field)
if field.name in kwargs and val is not MISSING: if field.name in kwargs and val is not MISSING:
# both *args and **kwargs specify the same thing # both *args and **kwargs specify the same thing
raise TypeError(f"got multiple values for argument '{field.name}'") raise TypeError(f"got multiple values for argument '{field.name}'")

View File

@ -158,7 +158,7 @@ if __name__ == "__main__":
if QT_VERSION_STR >= "5": if QT_VERSION_STR >= "5":
ok.clicked.connect(clicked) ok.clicked.connect(clicked)
elif QT_VERSION_STR >= "4": elif QT_VERSION_STR >= "4":
QObject.connect(ok, SIGNAL("clicked()"), clicked) # type: ignore ["QObject" is possibly unbound;;"SIGNAL" is possibly unbound] QObject.connect(ok, SIGNAL("clicked()"), clicked)
else: else:
raise RuntimeError("Unsupported Qt version") raise RuntimeError("Unsupported Qt version")

View File

@ -42,13 +42,15 @@ if TYPE_CHECKING:
from typing_extensions import Concatenate, ParamSpec from typing_extensions import Concatenate, ParamSpec
from .client import TrezorClient from . import client
from .protobuf import MessageType from .protobuf import MessageType
MT = TypeVar("MT", bound=MessageType) MT = TypeVar("MT", bound=MessageType)
P = ParamSpec("P") P = ParamSpec("P")
R = TypeVar("R") R = TypeVar("R")
TrezorClient = TypeVar("TrezorClient", bound=client.TrezorClient)
HARDENED_FLAG = 1 << 31 HARDENED_FLAG = 1 << 31
Address = NewType("Address", List[int]) Address = NewType("Address", List[int])
@ -154,7 +156,7 @@ def b58decode_int(v: str) -> int:
for char in v: for char in v:
decimal = decimal * __b58base + __b58chars.index(char) decimal = decimal * __b58base + __b58chars.index(char)
except KeyError: except KeyError:
raise ValueError(f"Invalid character {char!r}") from None # type: ignore [possibly unbound] raise ValueError(f"Invalid character {char!r}") from None
return decimal return decimal

View File

@ -124,7 +124,7 @@ class WebUsbTransport(ProtocolBasedTransport):
if cls.context is None: if cls.context is None:
cls.context = usb1.USBContext() cls.context = usb1.USBContext()
cls.context.open() cls.context.open()
atexit.register(cls.context.close) # type: ignore [Param spec "_P@register" has no bound value] atexit.register(cls.context.close)
if models is None: if models is None:
models = TREZORS models = TREZORS

1455
python/stubs/PIL/Image.pyi Normal file

File diff suppressed because it is too large Load Diff

View File

@ -213,7 +213,7 @@ def do_enumerate():
def do_acquire(path: str, sid: str): def do_acquire(path: str, sid: str):
check_origin() check_origin()
if sid == "null": if sid == "null":
sid = None # type: ignore [cannot be assigned to declared type] sid = None # type: ignore [is incompatible with declared type]
trezor = Transport.find(path) trezor = Transport.find(path)
if trezor is None: if trezor is None:
response.status = 404 response.status = 404

View File

@ -6,18 +6,20 @@ Function `get_address()` is showing the communication with ScriptUI
on a specific example on a specific example
""" """
from __future__ import annotations
import os import os
import subprocess import subprocess
from typing import Dict, List, Optional, Tuple, Union import typing as t
import click import click
def parse_args_from_line(line: str) -> Tuple[str, Dict[str, Union[str, bool]]]: def parse_args_from_line(line: str) -> tuple[str, dict[str, t.Any]]:
# ?PIN code=123 # ?PIN code=123
# ?PASSPHRASE available_on_device # ?PASSPHRASE available_on_device
command, *args = line.split(" ") command, *args = line.split(" ")
result: Dict[str, Union[str, bool]] = {} result = {}
for arg in args: for arg in args:
if "=" in arg: if "=" in arg:
key, value = arg.split("=") key, value = arg.split("=")
@ -27,7 +29,7 @@ def parse_args_from_line(line: str) -> Tuple[str, Dict[str, Union[str, bool]]]:
return command, result return command, result
def get_pin_from_user(code: Optional[str] = None) -> str: def get_pin_from_user(code: str | None = None) -> str:
# ?PIN # ?PIN
# ?PIN code=Current # ?PIN code=Current
while True: while True:
@ -47,7 +49,7 @@ def get_pin_from_user(code: Optional[str] = None) -> str:
def show_button_request( def show_button_request(
code: Optional[str] = None, pages: Optional[str] = None, name: Optional[str] = None code: str | None = None, pages: str | None = None, name: str | None = None
) -> None: ) -> None:
# ?BUTTON code=Other # ?BUTTON code=Other
# ?BUTTON code=SignTx pages=2 # ?BUTTON code=SignTx pages=2
@ -98,7 +100,7 @@ def get_address() -> str:
assert p.stdout is not None assert p.stdout is not None
assert p.stdin is not None assert p.stdin is not None
text_result: List[str] = [] text_result = []
while True: while True:
line = p.stdout.readline().strip() line = p.stdout.readline().strip()
if not line: if not line: