Skip to content

ctypes: improve bytes handling #9029

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

Merged
merged 3 commits into from
Oct 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions stdlib/ctypes/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ class _SimpleCData(Generic[_T], _CData):
class c_byte(_SimpleCData[int]): ...

class c_char(_SimpleCData[bytes]):
def __init__(self, value: int | bytes = ...) -> None: ...
def __init__(self, value: int | bytes | bytearray = ...) -> None: ...
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I failed to trace through the code for this, but I trust this is correct.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't find the code either but tried it in the REPL. This one allows bytearray but c_char_p doesn't.


class c_char_p(_PointerLike, _SimpleCData[bytes | None]):
def __init__(self, value: int | bytes | None = ...) -> None: ...
Expand Down Expand Up @@ -266,7 +266,11 @@ class Array(Generic[_CT], _CData):
def _type_(self) -> type[_CT]: ...
@_type_.setter
def _type_(self, value: type[_CT]) -> None: ...
raw: bytes # Note: only available if _CT == c_char
# Note: only available if _CT == c_char
@property
def raw(self) -> bytes: ...
@raw.setter
def raw(self, value: ReadableBuffer) -> None: ...
value: Any # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise
# TODO These methods cannot be annotated correctly at the moment.
# All of these "Any"s stand for the array's element type, but it's not possible to use _CT
Expand Down
2 changes: 2 additions & 0 deletions tests/stubtest_allowlists/py3_common.txt
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,8 @@ _ctypes.sizeof
# Allowlist entries that cannot or should not be fixed
# ==========

ctypes.Array.raw # exists but stubtest can't see it; only available if _CT == c_char

_collections_abc.AsyncGenerator.asend # async at runtime, deliberately not in the stub, see #7491. Pos-only differences also.
_collections_abc.AsyncGenerator.__anext__ # async at runtime, deliberately not in the stub, see #7491
_collections_abc.AsyncGenerator.aclose # async at runtime, deliberately not in the stub, see #7491
Expand Down