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

Add __class_getitem__ support to ctypes.py_object #132168

Closed
brianschubert opened this issue Apr 6, 2025 · 3 comments
Closed

Add __class_getitem__ support to ctypes.py_object #132168

brianschubert opened this issue Apr 6, 2025 · 3 comments
Labels
extension-modules C modules in the Modules dir topic-ctypes topic-typing type-feature A feature request or enhancement

Comments

@brianschubert
Copy link
Contributor

brianschubert commented Apr 6, 2025

Feature or enhancement

Proposal:

ctypes.py_object is generic in typeshed, but is not subscriptable at runtime. This can be troublesome for end users, since type checkers will prompt them to supply a generic type argument, but doing so will produce a TypeError at runtime:

>>> import ctypes
>>> ctypes.py_object[int]
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    ctypes.py_object[int]
    ~~~~~~~~~~~~~~~~^^^^^
TypeError: type 'py_object' is not subscriptable

(albeit this is partially mitigated by deferred annotations in 3.14, but TypeError can still pop up if the annotations are ever evaluated)

py_object's typeshed stubs have been stable for a while, and it seems unlikely to be made non-generic in the future. Therefore I propose that __class_getitem__ be added to ctypes.py_object so that it can be subscripted at runtime.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

python/typeshed#13760

Linked PRs

@picnixz
Copy link
Member

picnixz commented Apr 6, 2025

What's the reason for having ctypes.py_object generic actually? what does ctypes.py_object[int] means? does it mean a PyLongObject?

@sobolevn
Copy link
Member

sobolevn commented Apr 6, 2025

@brianschubert
Copy link
Contributor Author

It represents a pointer to an arbitrary Python object. Having it be generic lets you statically track the type of that object. I haven't written enough ctypes code to personally need it, but I imagine it being generic is useful if you need to access py_object.value, or if you need to type-hint a function whose behavior depends on the type of object that py_object is holding. It being generic also seems to be useful to numpy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
extension-modules C modules in the Modules dir topic-ctypes topic-typing type-feature A feature request or enhancement
Projects
None yet
Development

No branches or pull requests

4 participants