Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Shouldn't a slice of a bytestring be a bytestring? #9080

Closed
dvarrazzo opened this issue Nov 4, 2022 · 4 comments
Closed

Shouldn't a slice of a bytestring be a bytestring? #9080

dvarrazzo opened this issue Nov 4, 2022 · 4 comments

Comments

@dvarrazzo
Copy link

Slicing bytes, bytearray, memoryview objects, the result is an object of the same type.

However, slicing ByteArray, mypy complains:

from collections.abc import ByteString

def f(s: ByteString) -> ByteString:
    return s[10:20]
mypy test-bytestring-slice.py
test-bytestring-slice.py:4: error: Incompatible return value type (got "Sequence[int]", expected "ByteString")

Tested with mypy 0.982, 0.990 (from git).

Is this a typeshed shortcoming?

@JelleZijlstra
Copy link
Member

Don't use ByteString, it's basically useless. It declares no methods.

The behavior you see is because ByteString inherits __getitem__ from Sequence, and Sequence.__getitem__ doesn't guarantee that you get the same kind of Sequence back.

@dvarrazzo
Copy link
Author

Ok.

Mine was an attempt to replace the homegrown Buffer type in psycopg (defined as Union[bytes, bytearray, memoryview] - something supporting the Buffer protocol) with something from the stdlib.

I guess we'll keep our Buffer 😄

@hauntsaninja
Copy link
Collaborator

Yeah, would love to see the back of ByteString python/cpython#91896

@hauntsaninja hauntsaninja closed this as not planned Won't fix, can't repro, duplicate, stale Nov 4, 2022
@JelleZijlstra
Copy link
Member

In typeshed we have our own Buffer alias with a bunch more types: https://github.com/python/typeshed/blob/main/stdlib/_typeshed/__init__.pyi#L236. You can use it at type checking type (if TYPE_CHECKING: from _typeshed import ReadableBuffer).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants