为什么没有与“collections.abc.ByteString”相等的字符/代码点字符串?

2024-06-16 11:26:55 发布

您现在位置:Python中文网/ 问答频道 /正文

Python的collections.abc模块提供了SequenceMutableSequence抽象基类(ABC),它们包括strbytesbytearray和预期的类似类型

collections.abc还提供了一个ByteStringABC,它包括bytesbytearray和可能类似的类型。但是它没有为字符串或代码点(如str)提供ABC(这样的ABC可能被命名为StringCharStringCodepointString。)为什么它提供前者而不提供后者(换句话说,什么是需要前者而不是后者的预期用例?)


就像在中一样,子类型是isinstance()ABC


Tags: 模块字符串代码类型bytes基类命名collections
1条回答
网友
1楼 · 发布于 2024-06-16 11:26:55

添加^{}是为了让您能够测试出现在3.x文档中的“类字节类型”,而无需编写(bytes, bytearray)

事实上,它的docstring只是“这统一了字节和字节数组”

对Unicode字符串没有类似的需求,因为str是唯一这样的类型;没有什么可以统一的

您可以单击文档顶部的源代码链接,找到ByteString,然后git blame从GitHub GUI中直接找到the commit that added it。签入注释为:

Add ABC ByteString which unifies bytes and bytearray (but not memoryview).

There's no ABC for "PEP 3118 style buffer API objects" because there's no way to recognize these in Python (apart from trying to use memoryview() on them).

Note that array.array really should be registered as a MutableSequence but that would require importing it whenever collections is imported.

如果你真的想深入挖掘,可能会在2007年11月21日附近进一步讨论b.p.o.python-devpython-ideas邮件列表档案。但我怀疑这里是否还有更多的兴趣,因为这里真的没有什么可讨论的


注意^{}实际上确实有一个类型^{},它被记录为:

Text is an alias for str. It is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode.

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

正如文档中明确指出的那样,添加它不是为了在同一种语言中统一多个Unicode字符串类型,而是为了在静态类型检查时统一Python 2unicode和Python 3str

在运行时,如果您想要这个,您几乎肯定需要实际的strunicode构造函数,因此您可以使用类似^{}的东西

相关问题 更多 >