“bytes 或 bytearray”的正确类型注释是什么?

问题描述 投票:0回答:1

在 Python 3.11 或更高版本中,对于表示“字节的有序集合”的函数参数,是否有比

bytes | bytearray
更方便使用的类型注释?仅仅为了满足类型检查器的要求而要求从
bytes
(或相反)构造
bytearray
似乎很浪费。

请注意,该函数不会改变参数;从不同的调用站点传递

bytes
bytearray
实例非常方便。

例如

def serialize_to_stream(stream: MyStream, data: bytes | bytearray) -> None:
    for byte in data:
        stream.accumulate(byte)

(当然,这个例子是人为的,但目的是表明

data
只被读取,从未被改变)。

python python-typing
1个回答
1
投票

typing
模块曾经有一个类型来表示:
ByteString
。然而,它在 3.9 中已被弃用。

来自同一部分:

更喜欢

collections.abc.Buffer
,或者像
bytes | bytearray | memoryview
这样的联盟。

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.