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

Narrow input type annotation for GLib.Bytes.new #198

Open
phistep opened this issue Nov 14, 2024 · 3 comments
Open

Narrow input type annotation for GLib.Bytes.new #198

phistep opened this issue Nov 14, 2024 · 3 comments

Comments

@phistep
Copy link
Contributor

phistep commented Nov 14, 2024

The type annotation for GLib.Bytes.new() input argument data is confusingly narrow: Sequence[int].

def new(cls, data: typing.Optional[typing.Sequence[int]] = None) -> Bytes: ...

Yet the following code works without a problem:

import io

import gi
from gi.repository import GLib

data = b"hi mom."
array = GLib.Bytes.new(data)
array = GLib.Bytes.new(bytearray(data))
array = GLib.Bytes.new(memoryview(data))
array = GLib.Bytes.new(io.BytesIO(data).getvalue())

I think the type annotation should reflect this.

I made a PR that changes the type to typing.Union[typing.Sequence[int], bytes] but I'm neither sure that this will not have unwanted consequences for other classes nor that this is exhaustive for all the possible values shown above or what else might be legal to pass. I hope someone more knowledgeable can figure out what the maximal type annotation would be.

@phistep phistep changed the title Wrong input type annotation for GLib.Bytes.new Narrow input type annotation for GLib.Bytes.new Nov 14, 2024
@phistep
Copy link
Contributor Author

phistep commented Nov 14, 2024

It is possible that I am not familiar enough with the Python type system, since bytes() seems to be a compatible type to typing.Sequence[int]

$ mypy <(cat <<EOF
from typing import Sequence
def f(x: Sequence[int]): ...
f(bytes([0xff]))
EOF
)
Success: no issues found in 1 source file

I just find that very confusing?

@lovetox
Copy link
Collaborator

lovetox commented Nov 15, 2024

bytes is defined as sequence of integers

https://github.com/python/typeshed/blob/main/stdlib/builtins.pyi#L624

Still your question is valid if we cannot simply type it as bytes, i will think about that. Currently this may be confusing, but it will not yield any type errors.

@phistep
Copy link
Contributor Author

phistep commented Nov 15, 2024

Thanks for your consideration!

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

2 participants