You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add __class_getitem__ support to ctypes.py_object #132168
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:
>>>importctypes>>>ctypes.py_object[int]
Traceback (mostrecentcalllast):
File"<python-input-1>", line1, in<module>ctypes.py_object[int]
~~~~~~~~~~~~~~~~^^^^^TypeError: type 'py_object'isnotsubscriptable
(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
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.
Activity
picnixz commentedon Apr 6, 2025
What's the reason for having
ctypes.py_objectgeneric actually? what doesctypes.py_object[int]means? does it mean aPyLongObject?sobolevn commentedon Apr 6, 2025
@picnixz see https://github.com/python/typeshed/blob/2b7019b933ac8339e4ae8f4619a2a746446a8532/stdlib/ctypes/__init__.pyi#L253
brianschubert commentedon Apr 6, 2025
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
ctypescode to personally need it, but I imagine it being generic is useful if you need to accesspy_object.value, or if you need to type-hint a function whose behavior depends on the type of object thatpy_objectis holding. It being generic also seems to be useful to numpy.gh-132168: Add `__class_getitem__` to `ctypes.py_object` (#132169)