From 228c4db646a01425dad4e85695c9544924ddd929 Mon Sep 17 00:00:00 2001 From: matejcik Date: Wed, 5 Jan 2022 12:53:02 +0100 Subject: [PATCH] style(core): improve types in rlp.py --- core/src/trezor/crypto/rlp.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/core/src/trezor/crypto/rlp.py b/core/src/trezor/crypto/rlp.py index 0e892c16d..9f3d9c385 100644 --- a/core/src/trezor/crypto/rlp.py +++ b/core/src/trezor/crypto/rlp.py @@ -5,10 +5,16 @@ if TYPE_CHECKING: from typing import Union from trezor.utils import Writer - # what we want: - # RLPItem = Union[list["RLPItem"], bytes, int] - # what mypy can process: - RLPItem = Union[list, bytes, int] + # The intention below is basically: + # RLPItem = int | bytes | list[RLPItem] + # That will not typecheck though. Type `list` is invariant in its parameter, meaning + # that we cannot pass list[bytes] into a list[RLPItem] parameter (what if the + # function wanted to append an int?). We do want to enforce that it's a `list`, not + # a generic `Sequence` (because we do isinstance checks for a list). We are however + # only reading from the list and passing into things that consume a RLPItem. Hence + # we have to enumerate single-type lists as well as the universal list[RLPItem]. + RLPList = Union[list[int], list[bytes], list["RLPItem"]] + RLPItem = Union[RLPList, bytes, int] STRING_HEADER_BYTE = const(0x80) @@ -80,7 +86,7 @@ def write_string(w: Writer, string: bytes) -> None: w.extend(string) -def write_list(w: Writer, lst: list[RLPItem]) -> None: +def write_list(w: Writer, lst: RLPList) -> None: payload_length = sum(length(item) for item in lst) write_header(w, payload_length, LIST_HEADER_BYTE) for item in lst: